我正在構建Chrome擴展,當點擊工具欄圖標時,我正在執行background.js
,並在background.js
我正在運行執行腳本。就像這樣:通過background.js訪問網站變量與注入腳本
chrome.tabs.executeScript(null, { file: "libs/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "scripts/myScript.js" })
});
在myScript.js
,我可以證實,它已執行jQuery和運行我的腳本了。
myScript.js:
console.log('test');
$(document).ready(function() {
console.log('jQuery test');
})
他們都工作
在這一點上,我想實現一個變量,它是網頁(不是我寫的內);假設它是var helloWorld = "the content"
。
如果我嘗試在控制檯(開發工具),console.log(helloWorld)
,它的工作原理。不過,如果我嘗試在myScript.js
,它說:
$(document).ready(function() {
console.log(helloWorld)
setTimeout(function() {
console.log(helloWorld)
}, 1500)
})
Uncaught ReferenceError: helloWorld is not defined
我已經看到了一些解決方法爲內容腳本的做法,但我不能使它成爲executeScript方式工作。如何訪問myScript.js
中的helloWorld
變量?
我試過使用捕食者的方法。下面是代碼:
injected.js:
chrome.runtime.sendMessage("njfhnpgecmbmbipcjpkkglbkpcbjammb", {varName: "test"});
// I tried returning a string first
background.js
chrome.tabs.executeScript(null, { file: "libs/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "scripts/myScript.js" })
});
chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse){
console.log(message.varName);
if(message.varName !== undefined){
console.log(message.varName);
}
});
清單:
"background": {
"scripts": ["scripts/background.js"],
"persistent": true
},
根據您的第一個答案
,myScript.js
:
,myScript.js
:
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); //run the script
document.body.removeChild(script); //clean up
}
background.js
沒有趕上
我建議你閱讀[消息傳遞(https://developer.chrome.com/extensions/messaging)。 – PredatorIWD
如何讀取第三方網站DOM上的數據,以便我可以使用消息傳遞?我之前使用Message Passing在腳本之間進行通信(background.js和content_script.js),但我堅持問題的第一部分(在第三方網站DOM上閱讀js變量) – senty
您注入內容腳本,獲取變量然後將其發送到您的後臺腳本進行處理。 – PredatorIWD