I am making a chrome extension. I need to run a js script when the popup opens. How can I do that from background.js?
Asked
Active
Viewed 1,778 times
1
-
Possible duplicate of [How to interact with background.js from the popup?](http://stackoverflow.com/questions/9537435/how-to-interact-with-background-js-from-the-popup) – Cornwell May 31 '16 at 10:45
1 Answers
4
I am almost sure that this has already been asked and answered here, but it was easier to write it again than to find the existing question. You need to use 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
}
});

Petr Srníček
- 2,296
- 10
- 22