Call function in background from popup

Is there a way to call a function in the background of a script from a popup? I cannot explain this much further than this question. This is not a mistake that I encounter that I am trying to do, but something that I do not fully know how to do. I want to be able to click a button on a popup page that will call a function defined on the original page.

+10
function google-chrome-extension background popup call
source share
4 answers

try it

var bgPage = chrome.extension.getBackgroundPage(); var dat = bgPage.paste(); // Here paste() is a function that returns value. 
+23
source share

This is really possible using messaging .

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(); } ); 
+12
source share

You can just call the background.js functions in popup.js. You do not need to do anything extra. At least this is so for me.

Change: you probably need to add

"background": { "scripts": "background.js" }

in your manifest.json file.

+1
source share

You can use chrome.extension.sendMessage . But it is becoming obsolete. Use chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener .

0
source share

All Articles