title: Chrome Extension - How to message DOM from content script to background page?
body: <p>All I want to do is get copying text working in a chrome extension. I found this answer, <a href="https://stackoverflow.com/questions/7144702/the-proper-use-of-execcommandpaste-in-a-chrome-extension/7147192#7147192">the proper use of execcommand(&quot;paste&quot;) in a chrome extension</a>, which gives this copy() function:</p>
  
  <pre><code>function copy(str) {
      var sandbox = $('#sandbox').val(str).select();
      document.execCommand('copy');
      sandbox.val('');
  }
  </code></pre>
  
  <p>The problem is, it doesn't work if I put that on the background page and call it because the background page doesn't have access to the DOM elements (and can't access $('#sandbox')). So how can I send the DOM element $('#sandbox') from my content.js (which can access the DOM) script to my background.js script?</p>
  
  <p>I figured out how to send a message from my content.js script to my background.js script and receive a response through this:</p>
  
  <p>content.js:</p>
  
  <pre><code>$('#copybutton').click(function(){
         chrome.runtime.sendMessage({callCopyFunc: "callstart"}, function(response) {
            console.log(response.callCopyFunc);
          });
  });
  </code></pre>
  
  <p>background.js:</p>
  
  <pre><code>chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
      if(request.callCopyFunc == "callstart"){
          sendResponse({callCopyFunc: "callfinished"});
      }
  });
  </code></pre>
  
  <p>That works great! When I click the "copybutton" element on my webpage (just a button), content.js sends "callstart" to background.js and background.js sends back "callfinished" which is then displayed in the console log.</p>
  
  <p>My question is: How do I send the DOM element $('#sandbox') to the background.js file from content.js so I can use the copy() function on the background page itself? I'm not understanding how to actually send an element, only text.</p>
  
  <p>Sorry if this is really simple, I've been stuck on this for two days. Thanks!</p>