title: How to run callback function from content script after loading page ? chrome extension
body: <p>I want to run a callback function from content script after tab loading new page . </p>
  
  <p>Here is my code :</p>
  
  <p><strong>content_script.js</strong></p>
  
  <pre><code>chrome.runtime.onMessage.addListener(function(request, sender, callback) {
      if (request.id == "content_script") {
          // open google.com
          chrome.runtime.sendMessage({
              "id" : "openUrl",
              "url" : "https://google.com"
          }, function(response) {
          });
          // call background script
          // go to the claim code page
          chrome.runtime.sendMessage({
              "id" : "background"
          }, function() {
              alert("test");
          });
      }
  });
  </code></pre>
  
  <p><strong>background.js</strong></p>
  
  <pre><code>chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
      if (msg.id == "openUrl") {
          var tabId = sender.tab.id;
          var url = msg.url;
          openUrl(tabId, url);
  
      } else if (msg.id == "background") {
          setTimeout(function() {
              sendResponse();
          }, 5000);
      }
  
  });
  
  function openUrl(tabId, url) {
      chrome.tabs.update(tabId, {
          url : url,
          active : false
      }, function() {
          console.log("open tab url callback");
      });
  };
  </code></pre>
  
  <p>I also uploaded the source code to google drive, you can download it using the bellow link :
  <a href="https://drive.google.com/open?id=15zSn40z4zYkvCZ8B-gclzixvy6b0C8Zr" rel="nofollow noreferrer">https://drive.google.com/open?id=15zSn40z4zYkvCZ8B-gclzixvy6b0C8Zr</a></p>
  
  <p>as you can see the alert test don't show !</p>
  
  <p>However if I remove the code which open new url , then alert ("test") appear !</p>
  
  <p>I am not sure why ! but it looks like javascript lost the reference to the call back function when I open new url .</p>
  
  <p>How can I solve the problem ? what's the correct way ?</p>
  
  <p>Thank you </p>