我正在制作Chrome扩展程序。我需要在弹出窗口打开时运行js脚本。我怎么能从background.js那里做到这一点?
答案 0 :(得分:3)
我几乎可以肯定这已经被问到并在这里得到了解答,但是再次写它比找到现有问题更容易。您需要使用message passing。
<强>的manifest.json 强>
{
"manifest_version": 2,
"name": "My extension",
"description": "Start action in background from popup.",
"version": "1.0",
"browser_action": {
"default_title": "My extension",
"default_popup": "popup.html"
},
"background": {
"scripts": ["event.js"]
}
}
<强> popup.html 强>
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<p>Background page has been notified</p>
</body>
</html>
<强> popup.js 强>
chrome.runtime.sendMessage({text: "popup opened"});
<强> event.js 强>
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if (message.text == "popup opened") {
console.log ("Popup says it was opened.");
// Run your script from here
}
});