我可以安全地依赖主机名只为本地文件未定义(即导航到本地文件)吗?

我正在创建一个在每个页面上运行但仅在某些上下文中工作的网络扩展。这是 isSupported() 方法:


// return a boolean value that is true if the domain/page is supported, element name matches

// supported types, and content is marked as spell checkable

function isSupported (node, hostname) {

  const supportedNodeNames = ['TEXTAREA', 'DIV']

  const supportedDomains = ['mail.google.com', 'github.com']


  if (node.spellcheck && node.isContentEditable) {

    if (node.nodeName === 'TEXTAREA') {

      return true

    }


    if (supportedNodeNames.contains(node.nodeName) && supportedDomains.contains(hostname)) {

      return true

    }

  }


  return false

}

不幸的是,这段代码会阻止扩展程序在我的本地测试页面上运行,即当 URI 为 file:///home/username/github/multi-dict/test_page/test-page.html


我可以安全地依赖window.location.hostname未定义*并允许扩展在它出现时运行吗?我检查了MDN 上的文档和规范,但我不太清楚在什么确切的上下文中主机名是未定义的。


提前致谢!


*它实际上是一个空字符串,保留在读者/答案上下文的原始描述中。所以问题是 - 我可以安全地依赖window.location.hostname浏览器打开的本地文件是否为空 - 没有本地网络服务器正在运行。


慕虎7371278
浏览 158回答 1
1回答

浮云间

hostname被定义为字符串(MDN,spec),因此它不能具有 value undefined。在我尝试过的每个浏览器(Chrome、Firefox、IE、Edge)上"",它都是一个空字符串 ( ),而不是undefined。如果你认为它undefined在某些浏览器上,你可以做一个虚假检查:if (location.hostname) {    // It has a non-blank value} else {    // Its value is falsy (probably "", perhaps undefined)}但我认为它永远不会undefined。从规范:主机名属性的 getter 必须运行以下步骤:如果此Location对象的相关Document性为非空且其来源与条目设置对象的来源不同,则抛出“SecurityError”DOMException。如果此Location对象的 url 的主机是null,则返回空字符串。返回此Location对象的 urlhost序列化。(我的重点)本地 URL 的主机是null,因此步骤 2 中强调的部分适用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript