我有一个 chrome 扩展,它从后台脚本调用内容脚本以将 HTML 插入网页。
当我调用内容脚本 (inject.js) 时,我想从内容脚本 (eventpage.js) 传递一些参数,但这样做时遇到了一些麻烦。我也不想使用利用 chrome.storage 或 localstorage 的解决方案。
Manifest.json(相关部分):
{
"manifest_version": 2,
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["inject.js"]
}
],
...
"background": {
"scripts": ["eventpage.js",...],
"persistent": false
},
}
Eventpage.js(后台):
// Want to add the parameter here
chrome.tabs.executeScript(tabId, {
file: 'inject.js'
});
Inject.js(内容):
(function() {
// Want to retrieve the parameter passed from eventpage.js here
})();
最佳答案
使用messaging :
Eventpage.js
// Want to add the parameter here
var parameterToSend;
chrome.tabs.executeScript(tabId, {
file: 'inject.js'
}, function() {
chrome.tabs.sendMessage(tabId, {parameter: parameterToSend});
});
注入(inject).js
(function() {
// Want to retrieve the parameter passed from eventpage.js here
chrome.runtime.onMessage.addListener(function(message) {
var receivedParameter = message.parameter;
//use receivedParameter as you wish.
});
})();
关于javascript - 如何将参数从后台脚本传递到 chrome 扩展中的内容脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693659/