Pergunta

I'm sending the following message to content script:

chrome.tabs.sendMessage(activeTabId, {
    name:'executePageScript', 
    word:word, 
    isFirst:isFirst, 
    jq: function() {}
});

And listening to it in content script:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {})

The problem is that message object contains all keys except for the jq which holds reference to the function expression. If I change function expression to numerical or string literal, like this jq:3 or jq:"string", then the jq key is available in the message object. So it seems that I can't send function expressions (pointers to functions) to content script. Is it true? Or am I missing something?

Foi útil?

Solução

chrome.tabs.sendMessage works with messages as with JSON objects. (It serialise data before passing)

JSON specification not include functions i.e. all functions will be filtered before JSON serialisation.

The simple example:

var obj = {
  a: '1',
  b: 2,
  c: undefined,
  d: null,
  e: new Date(),
  f: function(){}
}
var str = JSON.stringify(obj);

UPDATE (workaround):

chrome.tabs.sendMessage(activeTabId, {
    name:'executePageScript', 
    word:word, 
    isFirst:isFirst, 
    jq: 'actionName1',
    jqParams: [1,2,3]
});

Other place:

runtimeRouter = {
  actionName1: function(a,b,c){
    console.log(arguments);
  }
}
runtime.onMessage(function(message, sender){
  if (message.jq && typeof runtimeRouter[message.jq] === 'function') {
    runtimeRouter[message.jq].apply(/*some context or null*/null, message.jqParams || []);
  }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top