是,包括腳本到頁面並運行從網頁運行腳本一個孤立的環境。
但是,可以通過將內聯腳本通過附加到文檔的html腳本標籤推入運行時上下文來解決孤立的世界問題。該內聯腳本然後可以拋出一個自定義事件。
孤立的上下文中包含的腳本可以監聽該事件並相應地作出響應。
因此,在你包含腳本代碼會是這個樣子:
// inject code into "the other side" to talk back to this side;
var scr = document.createElement('script');
//appending text to a function to convert it's src to string only works in Chrome
scr.textContent = '(' + function() {
var check = [do your custom code here];
var event = document.createEvent("CustomEvent");
event.initCustomEvent("MyCustomEvent", true, true, {"passback":check});
window.dispatchEvent(event); } + ')();'
//cram that sucker in
(document.head || document.documentElement).appendChild(scr);
//and then hide the evidence as much as possible.
scr.parentNode.removeChild(scr);
//now listen for the message
window.addEventListener("MyCustomEvent", function (e) {
var check = e.detail.passback;
// [do what you need to here].
});
這聽起來象是一個內容腳本應該做的,不是嗎? https://developer.chrome.com/extensions/content_scripts.html –
「但是,內容腳本有一些限制,它們不能:[...] 使用由網頁或其他內容腳本定義的變量或函數」 – kmoe
內容腳本在_isolated world_中執行。你將不得不將代碼注入頁面。 –