2015-05-04 85 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"] 
    } 
]