0

我正在嘗試修改Google的代碼注入sample code。文件manifest.json包括後臺腳本:如何從Chrome擴展中的內容腳本獲取變量?

"background": { 
    "scripts": ["background.js"], 
    "persistent": false 
    }, 

,我添加content script

"content_scripts": [ 
    { 
     "matches": ["*://*/*"], 
     "js": ["filter.js"] 
    } 
    ], 

現在我想,當用戶點擊擴展的按鈕呼叫filter.js定義功能foo()。我這樣做在background.js

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.executeScript({ 
    code: 'foo(testText);' 
    }); 
}); 

其中foo()filter.js定義爲

function foo(test) { 
    alert('Test: ' + String(test)); 
} 
var testText = 'foo'; 

我可以執行的功能,但無法通過testText變量。我得到VM3181:1 Uncaught ReferenceError: testText is not defined

我知道我指的是變量不正確,但如何做到這一點對嗎?

回答

1

看看sendMessageonMessage,從實例谷歌改變用途:

background.js

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.sendMessage(tab.id, {greeting: "foo"}, function(response) { 
     console.log(response.farewell); 
    }); 
}); 

而且在filter.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     if (request.greeting == "foo") { 
      //your Foo function can be called 
      sendResponse({farewell: "bar"}); 
     } 
}); 
相關問題