2015-05-04 45 views
2

我尝试通过原生javascript和聚合物从Chrome扩展中注册自定义元素,但没有运气。 The issue is documented here从Chrome扩展中注册自定义元素

Uncaught NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'polymer-element'. Elements cannot be registered from extensions. 

我在寻找关于在扩展中使用Web组件的建议 - 有没有人这样做?我的本能是在影子DOM上使用标准的html标签(div等)注册这些元素,直到它被支持。有什么建议么?

回答

7

确实有可能。但是,有点哈克。

原来的答案

步骤如下:

  • 本地Web组件(无聚合物)
    注意:这需要webcomponentsjs polyfill
    铬的使用将阻止原始registerElement在Chrome扩展中执行。为了克服它,你需要阻止使用本地registerElement来支持模拟的(polyfill)。 !

webcomponents-lite.js注释掉下面的代码(使这个更优雅,如果你想:

scope.hasNative = false; //Boolean(document.registerElement); 

瞧本地registerElement现在已经换成了填充工具 - 这Chrome不从使用扩展内防止。

  • 聚合物Web组件
    你将需要执行上述和另外的步骤列出的代码,则需要通过以下代码

    var link = document.createElement('link'); 
        link.setAttribute('rel', 'import'); 
        link.setAttribute('href', "link_to_your_polymer.html"); 
        link.onload = function() { 
        // Execute polymer dependent code here 
        } 
    

UPDATE#1到加载聚合物 - 改进溶液

后进一步调查,我已经了解到Polymer在动态加载时不能在扩展中工作。结果,上述修改是必要的。这种更简单的替代方法是负载聚合物进入头部在内容脚本这样的:

function loadRes(res) { 
    return new Promise(
     function(resolve, reject) { 
     var link = document.createElement('link'); 
     link.setAttribute('rel', 'import'); 
     link.setAttribute('href', res); 
     link.onload = function() { 
      resolve(res); 
     }; 
     document.head.appendChild(link); 
     }); 
    } 

    loadRes(chrome.extension.getURL("path_to_your_webcomponents-lite.js")) // You may/may not need webcomponents.js here 
    .then(loadRes(chrome.extension.getURL("path_to_your_polymer.html"))) 
    .then(loadRes(chrome.extension.getURL("path_to_your_custome_component"))) 
    .then(function(){ 
     // code that depends on web components 
    }); 

你必须添加由chrome.extension.getURL加载到您的清单的一部分web_accessible_resources的网址。

以上是必要的,因为polymer.html必须通过html资源加载。阅读Eric Bidelman's reply here

请注意,如果您的组件已经加载它们,你可能不需要在这里加载webcomponents填充工具。

+0

是因为你的一切注入到宿主页面真正需要的填充工具? – Ziyu

+0

可能不需要。我最初使用了polyfill,因为当我通过内容脚本加载聚合物时,“registerElement”不允许从chrome扩展中执行。现在我将这些资源加载到''''我相信你可以放弃polyfill。 –

+0

我不能使用这段代码。你能告诉我我的清单应该是什么样子吗?我的content_scripts被执行(与一起使用),但没有在我的popup.html中呈现,所以我认为这个文件没有被注入 – Cilenco

0

2017年7月到达此问题。我找到的直接解决方案是加载最新的webcomponents polyfill for custom elements作为额外的内容脚本。在polyfill文件中没有必要更改代码(可能功能检测已被改进)。从清单

提取物:

"content_scripts": [ 
    { 
     "matches": ["<all_urls>"], 
     "js": ["webcomponents-sd-ce.js", "contentscript.js"] 
    } 
]