Skip to content Skip to sidebar Skip to footer

Sending Data From Background.js To Extension.js In Crossrider

I am developing a browser extension using crossrider. I have added a context menu (background.js) var ContextData; appAPI.contextMenu.add('key1', 'Send Data To Server', func

Solution 1:

@Neel If I understand your requirements correctly, @Rob is essentially correct though a little clarification may help

By design/architecture, the extension.js code runs on each HTML page i.e. a separate extension.js instance is run for each URL that loads. In contrast, the context menu runs at the browser level (not HTML page) and is hence correctly coded in background.js file. However, the background.js code does not have direct access to the extension.js instance code running on the HTML page in the active tab and must therefore communicate the data via messaging. (For more information about scopes, see Scopes Overview)

Obviously, a user clicks the context menu item on the active tab (i.e. the page showing the HTML page being viewed); hence, once the ContextData string is created, you can use appAPI.message.toActiveTab to send the string to the extension.js instance running on the page/tab where the the context menu item was clicked.

This being the case, using your code example you can achieve this goal as follows:

background.js:

appAPI.ready(function($) {
  var ContextData;
  appAPI.contextMenu.add("key1", "Send Data To Server", function (data) {
    var ContextData = 'pageUrl: ' + data.pageUrl + '\r\n' +
      'linkUrl: ' + data.linkUrl + '\r\n' +
      'selectedText:' + data.selectedText + '\r\n' +
      'srcUrl:' + data.srcUrl;
    appAPI.message.toActiveTab({type:'dataToSend', data: ContextData});
  }, ["all"]);
});

extension.js:

appAPI.ready(function($) {
  var dataToSend =="test data";

  appAPI.message.addListener(function(msg) {
    if (msg.type === 'dataToSend') {
      appAPI.request.post({
        url: 'REST API URL',
        postData: dataToSend,
        onSuccess: function(response, additionalInfo) {
            var details = {};
            details.response = response;
        },
        onFailure: function(httpCode) {
          //  alert('POST:: Request failed. HTTP Code: ' + httpCode);
        }
      });   
    }
  });
});

[Disclaimer: I am a Crossrider employee]

Post a Comment for "Sending Data From Background.js To Extension.js In Crossrider"