我正在创建一个在每个页面上运行但仅在某些上下文中运行的网络扩展。这是 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和 the spec但我不太清楚在什么具体上下文中主机名将是未定义的。
提前致谢!
*它实际上是一个空字符串,保留在读者/答案上下文的原始描述中。所以问题是 - 我可以安全地依赖 window.location.hostname
仅对于浏览器打开的本地文件为空 - 没有本地网络服务器正在运行。
最佳答案
hostname
被定义为字符串( MDN 、 spec ),因此它不能具有值 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:
If this
Location
object's relevantDocument
is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.If this
Location
object's url's host isnull
, return the empty string.Return this
Location
object's url'shost
, serialized.
(我的重点)
本地 URL 的主机为 null
,因此步骤 2 中强调的部分适用。
关于javascript - 我可以安全地依赖仅对本地文件未定义的主机名(即导航到本地文件)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791666/