I want to call the function popup.js from background.js in Chrome extension.

Asked 1 years ago, Updated 1 years ago, 104 views

I have created the following code to do something like the title.However, the function does not ignite and there are no errors.How can I send data from background.js to popup.js?

background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  chrome.tabs.query({active:true, windowId:chrome.windows.WINDOW_ID_CURRENT}, function(result){
    chrome.tabs.sendMessage(result.shift().id, {
      command: "get_dom"
    },
    function(msg){
      console.log("result message:",msg);
      $.ajax({
        type: "POST",
        url: "http://localhost:3000",
        data —JSON.stringify({
          text —msg
        }),
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        crossDomain: true,
        success:function(data){
          console.log(data);
          var popup=chrome.extension.getViews({type:"tab"});
          if(popup.length>0){
            popup[0].showResult(data);
          }
        }
      })
    });
  });
});

popup.js

$( document).ready(function(){
  $('#submit').click(function(){
    console.log("cliecked");
    chrome.runtime.sendMessage({
      command: "get_text"
    });
  });

  function showResult(data){
    console.log(data);
    console.log("received message");
  }

});

javascript jquery chrome-extension

2022-09-30 19:23

1 Answers

First, in the title of this question,

I want to call popup.js function from background.js

That's true, but it's basically "Event page (=Background) calls to Popup page are not always possible."Popup page JavaScript Context is created when the Browser Action or Page Action button is pressed.In other words, popup.js is not loaded unless a pop-up is displayed.

However, if you look at the code above, it seems that popup.js to background.js, and then popup.js to background.js, so you can do this.There are several ways.

At first, the easiest way is to call the function defined in background.js directly.It looks like the following.

background.js

window.foo=(name)=>{
  return "Hello, "+name;
};

popup.js

chrome.runtime.getBackgroundPage(function(bg){
  let msg = bg.foo("Yoichiro");
  // Something...
});

If you would like to give a callback function to be called asynchronously later instead of returning it immediately, you can do the following:

background.js

window.foo=(name, callback)=>{
  callback("Hello,"+name);
};

popup.js

chrome.runtime.getBackgroundPage(function(bg){
  bg.foo("Yoichiro", (msg) =>{
    // Something...
  });
});

Now you can return the results of the background.js side to popup.js side.

Another method is to use chrome.runtime.sendMesasge().It is used in the code you provided, and I believe that the message from popup.js to background.js was successful.Now, how do I return the results from background.js to popup.js, but use the third argument ssendResponse を in the callback function of the onMessage event as follows:

background.js

chrome.runtime.onMessage.addListener(
  (msg, sender, sendResponse) = > {
    sendResponse("Hello," + msg.name);
  }
);

popup.js

chrome.runtime.sendMessage({
  name: "Yoichiro"
}, (msg) = > {
  // Something...
});

In other words, the value passed to the sendResponse() function is converted to the callback function call passed to the sendMessage(), and the value passed by the background.js side is obtained as an argument.


2022-09-30 19:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.