我有一個網頁,其中包含自己的腳本和變量,我需要執行這些腳本和變量并從擴展程序的Background.js中檢索返回值。我了解(我認為!),為了與網頁進行交互,必須通過chrome.tabs.executeScript或ContentScript完成此操作,但是因為代碼必須在原始頁面的上下文中執行(為了具有范圍) (腳本和變量),則需要先將其注入頁面。繼Rob W撰寫的精彩文章之后,我能夠調用頁面級腳本/變量,但是我正在努力了解如何以這種方式返回值。到目前為止,這就是我所得到的...網頁代碼(我想與之交互):<html><head><script> var favColor = "Blue"; function getURL() { return window.location.href; }</script></head><body> <p>Example web page with script content I want interact with...</p></body></html>manifest.json:{ // Extension ID: behakphdmjpjhhbilolgcfgpnpcoamaa "name": "MyExtension", "version": "1.0", "manifest_version": 2, "description": "My Desc Here", "background": { "scripts": ["background.js"] }, "icons": { "128": "icon-128px.png" }, "permissions": [ "background", "tabs", "http://*/", "https://*/", "file://*/", //### (DEBUG ONLY) "nativeMessaging" ]}background.jscodeToExec = ['var actualCode = "alert(favColor)";', 'var script = document.createElement("script");', ' script.textContent = actualCode;', '(document.head||document.documentElement).appendChild(script);', 'script.parentNode.removeChild(script);'].join('\n');chrome.tabs.executeScript( tab.id, {code:codeToExec}, function(result) { console.log('Result = ' + result);} );我意識到代碼當前只是在“更改” favColor變量(這只是一項測試,以確保我可以看到它正常工作)。但是,如果我嘗試返回該變量(通過將其保留為最后一條語句或說“ return favColor”),則executeScript回調將永遠沒有該值。因此,這里似乎有(至少)三個級別:background.js內容腳本實際網頁(包含腳本/變量)...我想知道從1級到3級(以上)并返回值的推薦方式是什么?在此先感謝:o)
從Background.js在頁面級執行代碼并返回值
飲歌長嘯
2020-01-06 14:45:06