[英]Chrome Extension: executeScript on tab
我最近開始開發我的第一個 Google Chrome 擴展程序,並且遇到了一個我不完全確定如何解決的問題。
在我的腳本中,我正在檢查一個選項卡是否對特定網站打開,如果是,我正在執行以下代碼:
chrome.tabs.update(tab.id, {active: true});
// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
"code": "messageOpen(15, false);"
});
上面的代碼應該更新選項卡,將其設置為活動狀態,然后嘗試執行一個名為messageOpen()
的函數。 我遇到的問題是函數messageOpen()
作為包含在我網站的<HEAD>
中的函數存在,但不是我的擴展。
因此,當嘗試執行messageOpen()
函數時,我收到此錯誤:
Uncaught ReferenceError: messageOpen is not defined
如果我定期瀏覽網站,我 100% 肯定messageOpen()
函數可以工作,但是在使用executeScript
時,就好像擴展無法運行已在我的活動選項卡中加載的函數。
有沒有人有一些建議或替代方案?
發生這種情況是因為內容腳本無法與它們被注入到的頁面的window
對象進行交互。 如果要執行使用messageOpen()
函數的腳本,則必須使用<script>
將該代碼注入頁面上下文,如下所示:
var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);
因此,如果您想使用executeScript()
方法和"code"
屬性注入此代碼,您可以這樣做:
chrome.tabs.update(tab.id, {active: true});
// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
"code": "var myScript = document.createElement('script');"
+ "myScript.textContent = 'messageOpen(15, false);';"
+ "document.head.appendChild(myScript);"
});
注意:自 2021 年 1 月起,使用Manifest V3和chrome.scripting.executeScript()
而不是chrome.tabs.executeScript()
。
這是在 Manifest v3 的選項卡上執行 js 的工作示例:
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => {
// write your code here
document.body.style.backgroundColor = "red";
},
});
您還需要將scripting
權限添加到 Manifest.json
permissions: [
'scripting', // to execute js into a tab
],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.