Chrome extension message being passed as object

a 夏天 提交于 2019-12-18 09:44:45

问题


I'm sending a message from the content script to the background page. The message is a URL which then gets ajax parsed in the background. When I console.log the data retrieved into background.js the console log is pure html, but when I send the message back to my content script the message is suddenly in an object, and I'm not sure why.

Here is my code:

Content_Script.js:

chrome.runtime.sendMessage({greeting: URL}, function(response) {
      console.log(response.farewell); //logs an object: Object {farewell: Object}
      $('#stats-table2').append(response.farewell); //doesn't output anything.
    });

Background.js:

chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {
      getStats(message, sender, sendResponse);
      return true;
});

function getStats(message, sender, sendResponse){
   $.ajax({
     url: message.greeting,
     dataType: 'text',
     success: function(data) {
          var info = $("<div>").html(data)[0].getElementsByTagName("table")[1];
          if(info != undefined) {
            console.log(info); //logs pure HTML into the console..
            sendResponse({farewell:info}); //sends message back.
          }

      }
  });
}

I have added comments for the important parts.. I can't seem to figure this out and it's driving me crazy. Any ideas? Thanks!


回答1:


You can't pass DOM nodes with Messaging; data must be JSON-serializable, and DOM nodes are not.

Pass only data you really need (e.g. textContent), then reconstruct the node on the other side.



来源:https://stackoverflow.com/questions/32341102/chrome-extension-message-being-passed-as-object

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