javascript - 我可以安全地依赖仅对本地文件未定义的主机名(即导航到本地文件)吗?

标签 javascript hostname window.location

我正在创建一个在每个页面上运行但仅在某些上下文中运行的网络扩展。这是 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并允​​许扩展在未定义时运行吗?我检查了文档 MDNthe spec但我不太清楚在什么具体上下文中主机名将是未定义的。

提前致谢!

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

最佳答案

hostname 被定义为字符串( MDNspec ),因此它不能具有值 undefined。在我尝试过的每个浏览器(Chrome、Firefox、IE、Edge)上,它都是一个空字符串(""),而不是未定义。如果您认为它在某些浏览器上未定义,您可以进行错误检查:

if (location.hostname) {
    // It has a non-blank value
} else {
    // Its value is falsy (probably "", perhaps undefined)
}

但我不认为它是未定义的。来自 spec :

The hostname attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this Location object's url's host is null, return the empty string.

  3. Return this Location object's url's host, serialized.

(我的重点)

本地 URL 的主机为 null,因此步骤 2 中强调的部分适用。

关于javascript - 我可以安全地依赖仅对本地文件未定义的主机名(即导航到本地文件)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791666/

相关文章:

c# - 主机名和域名有什么区别(语法上)

javascript - 如何仅使用 JavaScript 首先导航到不同的 href,然后让代码继续?

javascript - 如何使用javascript从第二页到第一页进行通信?

javascript - 为什么在选择开始时使用 removeAllRAnges()?

javascript - 如何拆分字符串对象然后连接并添加到数组

javascript - 谷歌授权弹出窗口卡在 chrome 扩展中

javascript - 如何在 TypeScript 组件中使用 Observable 的值 | Angular 4

installation - 如何使用 WIX 更改我的 DNS 主机名

c - 在 C 中使用 LwIP 设置 DHCP 选项

javascript - electron 的 remote.getGlobal() 在 window.location.replace() 之后返回 "undefined"