Chrome扩展程序消息作为对象传递 [英] Chrome extension message being passed as object

查看:107
本文介绍了Chrome扩展程序消息作为对象传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从内容脚本向后台页面发送消息。该消息是一个URL,然后在后台获取ajax解析。当我将console.log中的数据检索到 background.js 时,控制台日志是纯html,但是当我将消息发送回内容脚本时,消息突然出现在对象,我不知道为什么。



以下是我的代码:


Content_Script.js:




  chrome.runtime.sendMessage({greeting:URL},function (response){
console.log(response.farewell); //记录一个对象:Object {farewell:Object}
$('#stats-table2')。append(response.farewell); //不输出任何内容
});




Background.js: blockquote>

  chrome.runtime.onMessage.addListener(
函数(message,sender,sendResponse){
getStats(message ,sender,sendResponse);
返回true;
});

函数getStats(message,sender,sendResponse){
$ .ajax({
url:message.greeting,
dataType:'text',
成功:function(data){
var info = $(< div>)。html(data)[0] .getElementsByTagName(table)[1];
if(info !$ =
console.log(info); //将纯HTML写入控制台..
sendResponse({farewell:info}); //发送消息
}

}
});
}

我为重要部分添加了评论..我似乎无法弄明白这一点,这让我发疯。有任何想法吗?感谢!

解决方案

您无法通过消息传递DOM节点;数据必须是JSON序列化的,而DOM节点不是。

只传递你真正需要的数据(例如 textContent ),然后重建另一侧的节点。

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!

解决方案

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.

这篇关于Chrome扩展程序消息作为对象传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆