当弹出窗口在chrome扩展中打开时,如何从background.js触发某些操作

时间:2016-05-31 07:53:47

标签: google-chrome-extension

我正在制作Chrome扩展程序。我需要在弹出窗口打开时运行js脚本。我怎么能从background.js那里做到这一点?

1 个答案:

答案 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
    }
});