Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - Chrome extension message being passed as object

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...