-2

我希望我的插件可以在加載任何頁面並更改它的某些內容時工作,因爲我編寫了內容腳本,並添加了外部js文件,在外部js文件中我無法訪問chrome.tab。*我做錯了嗎?內容腳本無法訪問chrome.tabs。*即使在添加外部js文件後

------內容腳本----

debugger; 
var s = document.createElement('script'); 
      s.src = chrome.extension.getURL("script.js"); 
      (document.head||document.documentElement).appendChild(s); 
      s.parentNode.removeChild(s); 


      /*chrome.runtime.sendMessage('3645374', 'any message',[] , function(){ alert('---...---'); })  ; 

chrome.tabs.executeScript(null, {file: "doWhatYouWant();"}); 


document.addEventListener('DOMContentLoaded', function() { 
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
     if (changeInfo.status == 'complete') { 
      var s = document.createElement('script'); 
      s.src = chrome.extension.getURL("script.js"); 
      (document.head||document.documentElement).appendChild(s); 
      s.parentNode.removeChild(s); 
      chrome.tabs.executeScript(null, {code:"doWhatYouWant();"}); 
     } 
    }); 
});*/ 

--------------------的script.js ---- ----------

function doWhatYouWant(){ 
    alert('inside .... doWhatYouWant'); 
    document.getElementById('zx12').value = "CHANGED !"; 
} 


chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if (changeInfo.status == 'complete') { 
    debugger; 
     alert('I am here too '); 
     // Execute some script when the page is fully (DOM) ready 
     chrome.tabs.executeScript(null, {code:"doWhatYouWant();"}); 
    } 
}); 


/*chrome.extensions.onRequest.addLiestener(function(p1,p2,p3){ 
    alert('done'); 
    document.getElementById('zx12').value = "CHANGED !"; 
}); 



chrome.runtime.onMessage.addListener(function(){ 
    alert('doWhatYouWant called'); 
}); 



document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('zx12').value = "CHANGED !"; 
}); 
*/ 

----------------------- manifest.json ------- --------

{ 
    "name": "My Chrome Extension", 
    "version": "1.0", 
    "manifest_version": 2, 
    "content_scripts": [{ 
     "matches": ["http://*/*","https://*/*"], 
     "js": ["jquery.js","contentscript.js"] 
    }], 
    "web_accessible_resources" : ["script.js"], 
    "permissions": [ 
    "activeTab" 
    ] 
} 

回答

2

內容腳本不能使用大多數Chrome擴展API。 (您正在調用的chrome.extension.getURL是罕見的例外。)您可能需要在擴展的後臺頁面中實現chrome.tabs事件偵聽器,並將消息傳遞給內容腳本。

請閱讀the Google Chrome documentation on content scripts,特別是關於限制的介紹部分和執行環境部分。