Is there a way to call a function in the background script from the popup? I can't explain it much further than that question. It's not an error I'm having with what I'm trying to do but rather something I completely don't know how to do. I want to make it possible to click a button in the popup page that'll call a function defined in the background page.
Asked
Active
Viewed 1.4k times
12
-
Possible duplicate of [How to communicate between popup.js and background.js in chrome extension?](https://stackoverflow.com/questions/13546778/how-to-communicate-between-popup-js-and-background-js-in-chrome-extension) – GorvGoyl Nov 29 '17 at 05:27
4 Answers
26
Try this
var bgPage = chrome.extension.getBackgroundPage();
var dat = bgPage.paste(); // Here paste() is a function that returns value.
Exception
- 7,721
- 19
- 82
- 133
-
-
Worked, but I had to define my function as `window.myFun = ...` instead of just `function myFun ...` – JellicleCat Apr 28 '20 at 16:37
15
It is indeed possible, using Message Passing.
popup.js
$("#button").click(function(){
chrome.runtime.sendMessage({ msg: "startFunc" });
});
background.js
var func = function(){
alert("Success!");
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
if(request.msg == "startFunc") func();
}
);
mattsven
- 20,501
- 10
- 66
- 102
1
You can just call background.js functions in popup.js. You don't need to do anything extra. At least that is the case for me.
Edit: you probably need to add
"background": {
"scripts": "background.js"
}
in your manifest.json file.
Shunya Watanabe
- 190
- 2
- 8
0
You can still use chrome.extension.sendMessage.
But that is getting deprecated.
Use chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener instead.
Derrick
- 1,368
- 9
- 8