Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: dealing with asynchronous sendMessage.

I'm working on a chrome extension that extracts meta data. The code which parses the metadata is contained in a content script. The background.js and content.js communicates via a sendMessage request and response. I'm running into an issue with the asynchronous nature of the sendMessage request and I'm not sure how to fix it (even after reading a litany of the discussions on the issue). Any advice or direction would be appreciated. I suspect I'm not getting how to turn these into callbacks.

background.js:

function onContextClick(info, tab) {    
  if( info["selectionText"] ){  
    var x = getMeta(tab);   
    //do stuff with x       
  }
}

function getMeta (tab) {
chrome.tabs.sendMessage(tab.id, {fetchTag: "meta,name,author,content"}, function(response) {
    //alert(response.data);
    //one thing I tired was to put my "do stuff" embedded here, but that didn't work either         
    return response.data; 
    });
}

var menu_id = chrome.contextMenus.create({"title": "Get Meta", "contexts":["selection"], "onclick": onContextClick});

content.js:

function fetchTag(string) {
    var param = string.split(",");
    return $(param[0] + "["+param[1]+ "=\"" + param[2] + "\"]").attr(param[3]); 
    }

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.fetchTag.length > 0)        
    sendResponse({data: fetchTag(request.fetchTag)});
  });
like image 530
Steven DAmico Avatar asked Apr 26 '26 06:04

Steven DAmico


1 Answers

From: https://developer.chrome.com/extensions/runtime#event-onMessage

Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.fetchTag.length > 0)        
    sendResponse({data: fetchTag(request.fetchTag)});
    return true;
});

And then it will work with async code.

like image 108
Yandimirkin Vladislav Avatar answered Apr 30 '26 18:04

Yandimirkin Vladislav