0

I want an event page to get a variable from the content script that sends it a message. As far as I know, I can only send a simple JSON message to the event page, such as {greeting: "hello"}.

How can I send a variable from the content script to the event page?

I've looked into JSON.stringify() to send the variable through the JSON message but I haven't had any luck.

trincot
  • 317,000
  • 35
  • 244
  • 286
dlegs
  • 1
  • 1

2 Answers2

0

Say you have a variable named VAR, you could directly send it via chrome.runtime.sendMessage without doing anything, because the message is automatically JSON-serialized.

chrome.runtime.sendMessage({ data: VAR });
Community
  • 1
  • 1
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
-1

You can pass stringify your object when sending the message from your content script and then parse it in your event page when you receive it.

Content Script

var myObj = {};
chrome.runtime.sendMessage({data: myObj}, function(response) {

});

Event Page

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      var data = request.data;
});
10100111001
  • 1,832
  • 1
  • 11
  • 7
  • [the message is automatically JSON-serialized](http://stackoverflow.com/questions/38234925/does-chrome-extension-internally-use-json-stiringify-to-postmessage-over-to-back) – wOxxOm Jul 26 '16 at 07:08