2013-05-02 54 views
25

我正在構建Chrome擴展程序,並且需要在幾個網站上覆蓋一個html blob。目前,我正在使用JQuery .Get從我的服務器中提取html。爲了提高性能,我想知道是否可以將html作爲文件包含在擴展目錄中並直接從那裏訪問源代碼?有誰知道這是否可能?將HTML注入到內容腳本的頁面中

UPDATE

羅布的建議下做這項工作(見接受的答案)。唯一的額外步驟是在清單web_accessible_resources下注冊該文件。

{ 
    ... 
    "web_accessible_resources": [ 
    "myimportfile1.html", 
    "myimportfile2.html" 
    ], 
    ... 
} 

回答

37

是的,這是可能的。使用chrome.extension.getURL獲取資源的絕對URL。例如:

步驟1:

$.get(chrome.extension.getURL('/template.html'), function(data) { 
    $(data).appendTo('body'); 
    // Or if you're using jQuery 1.8+: 
    // $($.parseHTML(data)).appendTo('body'); 
}); 

步驟2:

註冊資源在清單下web_accessible_resources:見https://developer.chrome.com/extensions/manifest#web_accessible_resources(由@QFDev提供)

+5

完美的作品,謝謝!唯一的額外步驟是將資源註冊到web_accessible_resources下的清單中:http://developer.chrome.com/extensions/manifest.html#web_accessible_resources – QFDev 2013-05-02 14:07:18

+0

@QFDev,您將這些代碼放在哪裏? – Chamnap 2015-12-05 07:27:42

+1

@Chamnap在我的情況下,我在我的內容腳本中有這個代碼。 – QFDev 2015-12-05 12:50:20

5

這是我的方法:

var xmlHttp = null; 

xmlHttp = new XMLHttpRequest(); 
xmlHttp.open("GET", chrome.extension.getURL ("src/inject/inject.html"), false); 
xmlHttp.send(null); 

var inject = document.createElement("div"); 
inject.innerHTML = xmlHttp.responseText 
document.body.insertBefore (inject, document.body.firstChild); 

沒有jQuery等

+0

看起來像Chrome瀏覽器已在主線程上棄用XMLHttpRequest()。這就是當我爲browserAction採用此代碼時所得到的結果。單擊方法: '主線程上的同步XMLHttpRequest已棄用,因爲它對最終用戶的體驗有不利影響。如需更多幫助,請查看http:// xhr.spec.whatwg.org/.' – baskint 2015-10-28 15:24:33

+2

將'.open()'的最後一個參數更改爲'true',它將是異步的 – Kamil 2015-10-28 18:35:04

+0

爲了使異步,我必須更改最後一個將'.open()'的參數設置爲'true',並將最後三行代碼包裝在'xmlHttp.onload = function(){...} – richardkmiller 2017-08-09 13:52:28

0

如果您使用您的Chrome擴展角,你可以利用ng-include

var injectedContent = document.createElement("div"); 
injectedContent.setAttribute("ng-include", ""); 
//ng-include src value must be wrapped in single quotes 
injectedContent.setAttribute("src", "'" + chrome.extension.getURL("template.html") + "'"); 
existingElement.appendChild(injectedContent); 
1

我用這個代碼。它只有3行代碼,你不需要任何jQuery的垃圾。

var iframe = document.createElement ('iframe'); 
iframe.src = chrome.extension.getURL ('iframe.html'); 
document.body.appendChild (iframe); 
0

做的另一種方法是使用新的Fetch API

如果該文件的名稱是modal.html - 更新manifest.json相應

"web_accessible_resources": [ 
    "modal.html", 
], 

,並注入這樣說:

fetch(chrome.extension.getURL('/modal.html')) 
    .then(response => response.text()) 
    .then(data => { 
     document.body.innerHTML += data; 
     // other code 
     // eg update injected elements, 
     // add event listeners or logic to connect to other parts of the app 
    }).catch(err => { 
     // handle error 
    }); 
相關問題