title: Accessing a pages object using a Chrome Extension
body: <p>I simply have to access an object that is a variable on the page that I am running my content script on from my Chrome Extension.</p>
  
  <p>I know about the environments and their isolated worlds in which the content scripts and injected scripts run and that it's possible to get some variables using the injected scripts and then send them back.</p>
  
  <p>I have searched for other answers regarding this question and most work for other type of variables and are the basic way of doing it but none currently work for accessing objects.</p>
  
  <p>Any current solutions or workarounds?</p>
  
  <p><strong>EDIT: The solution that I used:</strong></p>
  
  <p>Content script:</p>
  
  <pre><code>//Sends an object from the page to the background page as a string
  window.addEventListener("message", function(message) {
      if (message.data.from == "myCS") {
          chrome.runtime.sendMessage({
              siteObject: message.data.prop
          });
      }
  });
  var myScript = document.createElement("script");
  myScript.innerHTML = 'window.postMessage({from: "myCS", prop: JSON.stringify(OBJECT)},"*");';
  document.body.appendChild(myScript);
  </code></pre>
  
  <p>Background.js:</p>
  
  <pre><code>//Info receiver
  chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  
      //When the content script sends the sites object to extract the needed data
      if (message.siteObject !== undefined) {
          console.log(message.siteObject);
          //Process the data
      }
  
  });
  </code></pre>