How to send data from popup script to background.js in crossrider?

我只是一个虾纸丫 提交于 2019-12-12 02:32:48

问题


I am developing a browser extension using crossrider. I have some resource pages like popup.html and popup.js. In popup.html, there is a form and when user submit the form I want to send the data to my server, which is straight forward. But I also want to send the active tab url along with the form data. But we can get the active tab url in background.js only. To do this I need to send the form data to background.js and then post them to my server.

So my question is how to send data from popup.js (popup window) to background.js ?


回答1:


In answer to your direct question, you can send data from the popup scope to the background scope using appAPI.message.toBackground.

However, I think it would be more efficient to get the active tab's URL when the popup is opened so that it's available in the popup when the form is submitted. You can achieve this by requesting the active tab's URL directly from the active tab and saving the response in a var in the popup scope, as follows:

popup.html:

function crossriderMain($) {
  // var to store active tab's URL
  var activeTabUrl = null;

  // Message listener for response from active tab
  appAPI.message.addListener(function(msg) {
    if (msg.type === 'active-tab-url') activeTabUrl = msg.url;
  });

  // Request URL from active tab
  appAPI.message.toActiveTab({type: 'active-tab-url'});

  // THE REST OF YOUR CODE
}

extension.js:

appAPI.ready(function($) {
  // Message listener
  appAPI.message.addListener(function(msg) {
    if (msg.type === 'active-tab-url')
      // Send active tab's URL to popup
      appAPI.message.toPopup({
        type: 'active-tab-url',
        url:encodeURIComponent(location.href)
      });
  });

  // THE REST OF YOUR CODE
});

[Disclaimer: I am a Crossrider employee]



来源:https://stackoverflow.com/questions/21017681/how-to-send-data-from-popup-script-to-background-js-in-crossrider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!