代码之家  ›  专栏  ›  技术社区  ›  GrayedFox

我是否可以安全地依赖未定义本地服务内容的主机名(即开发/测试/本地文件)?

  •  0
  • GrayedFox  · 技术社区  · 5 年前

    我正在创建一个web扩展,它运行在每个页面上,但只在特定的上下文中工作。下面是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 但我不太清楚在什么样的上下文下主机名是未定义的。

    提前谢谢!

    窗口.location.hostname 仅当浏览器打开的本地文件为空时-没有运行本地Web服务器。

    1 回复  |  直到 5 年前
        1
  •  1
  •   T.J. Crowder    5 年前

    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 :

    1. 如果这个 Location 对象相关 Document 是非空的,并且其源域与entry settings对象的源域不同,然后抛出一个“SecurityError”DOMException。

    2. 如果这个 对象的url主机是 null 返回空字符串。

    3. 把这个还给我 位置 host ,序列化。

    (我强调)

    本地url的宿主是 无效的