title: Passing a DOM element from background.js to content_script.js
body: <p>(I will refer to background.js as <strong>ba.js</strong> and content_script.js as <strong>cs.js</strong>)</p>
  
  <p><strong>Scenario:</strong> </p>
  
  <ol>
  <li><strong>cs.js</strong> is being injected in every webpage.</li>
  <li>User might click a context menu button to display a modal on the main webpage.</li>
  <li>So, this means creating a modal (which has many sub elements and handlers) every time button is clicked.</li>
  <li>So, I decided to create one element in <strong>ba.js</strong> and then pass it as a message using <strong>chrome.tabs.sendMessage</strong> to <strong>cs.js</strong></li>
  </ol>
  
  <p><strong>Problem:</strong></p>
  
  <p>An empty object (<code>{}</code>) is being received in <strong>cs.js</strong>. See logs of <strong>ba.js</strong>:</p>
  
  <p><a href="https://i.stack.imgur.com/NqgB5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NqgB5.png" alt="enter image description here"></a></p>
  
  <p>But then see log of <strong>cs.js</strong>:</p>
  
  <p><a href="https://i.stack.imgur.com/9QrJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9QrJS.png" alt="enter image description here"></a></p>
  
  <p><strong>Question:</strong></p>
  
  <p>What's the problem and how can I send a DOM element from <strong>ba.js</strong> to <strong>cs.js</strong>?</p>
  
  <h3>Relevant Code:</h3>
  
  <p><strong>ba.js</strong>:</p>
  
  <pre><code>(function(){
      chrome.contextMenus.create({
          type: "normal",
          id: "x",
          title: "Click me!",
      });
  
      chrome.contextMenus.onClicked.addListener(function(info, tab){
          var id = info.menuItemId,
              url = info.pageUrl,
              elm = document.createElement("div");
  
          elm.classList.add("test");
          elm.appendChild(document.createElement("span"));
  
          console.log("Element", elm);
  
          if(id === "x"){     
              msg = {
                  task: "doWork",
                  elm: elm
              };
  
              chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
                  console.log(msg);
                  chrome.tabs.sendMessage(tabs[0].id, msg);
              });
          }
      }); 
  })();
  </code></pre>
  
  <p><strong>cs.js</strong>:</p>
  
  <pre><code>(function(){
      chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {          
          if(request.task === "doWork")
              console.log(request.elm);
      });
  })();
  </code></pre>
  
  <p><strong><a href="https://drive.google.com/file/d/0B-MHagh5cA4MQUh1SGtwOElpNnM/view?usp=sharing" rel="nofollow noreferrer">Zip file of files to install and check manually</a></strong></p>
  
  <p>I have included all relevant info. If you may feel something is missing, please tell me. Please include well researched answers. Thanks!</p>