Call a function in background from popup

13,694

Solution 1

Try this

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

Solution 2

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();
    }
);

Solution 3

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.

Share:
13,694

Related videos on Youtube

Anonymous
Author by

Anonymous

Updated on May 22, 2020

Comments

  • Anonymous
    Anonymous almost 4 years

    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.

  • Auspex
    Auspex over 8 years
    I knew I could do this, just needed to find an example. Thanks.
  • JellicleCat
    JellicleCat almost 4 years
    Worked, but I had to define my function as window.myFun = ... instead of just function myFun ...

Related