0

I use XMLHttpRequest in content script. The code works whenever a new tab opens, but it stops working whenever a tab is updated. tabupdation API only works in background.

Manifest:

{
    "manifest_version": 2,

    "name": "extension",
    "version": "1.0",
    "description": "",
    "icons" : {
        "48" : "48X48.png",
        "128": "icon1.png"
    },

    "background": {
        "scripts":    ["background.js"],
        "persistent": true    
    },    
    "content_scripts": [{
        "matches":    ["<all_urls>"],
        "js":         ["content.js"],
        "all_frames": true
    }]
}

The content script uses XMLHttpRequest.

var string="string on web page ";

 xmlhttp=new XMLHttpRequest();


xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {

alert(xmlhttp.responseText);
}
}
 xmlhttp.open("GET","url/folderName/file.php?q=string",true,"userName","password");

 xmlhttp.send();

string is actually the value which i retrieved from web page and send in xHR but when tab url changes previous values are displayed instead of new one. This code does not work whenever i open url in current tab e.g. as we do in youtube, open video suggested on side but if we open any video in new tab then content script work/if we reload that tab then content script worked.

mano
  • 85
  • 1
  • 3
  • 17
  • You probably need add some permissions, but unless we see some more code, we can only take guesses (which isn't neither much helpful nor much fun). Please, post the relevant code. – gkalpak Dec 04 '13 at 20:14
  • Is this the whole code ? Where do you send the XHR ? – gkalpak Dec 04 '13 at 21:17
  • sorry now see the code . I dont know whats the problem. why on tab updation the code is not working – mano Dec 04 '13 at 22:17
  • How do you retrieve the string from the web page? (eg. $(document).ready(…)?) – Marc Dec 05 '13 at 06:08
  • @mano: Did you take a look at my answer below ? Did it answer your question ? If so, please consider marking it as "accepted". – gkalpak Dec 14 '13 at 16:30
  • actually the answers which worked i have accepted but which does not work i dont accept. but i always say thanks to people which give response. but i will consider your suggestion np :) – mano Dec 19 '13 at 04:39

1 Answers1

2

You have probably misunderstood the concept of the chrome.tabs.onUpdated event. It does not fire when the content of a tab's web-page is updated, but when the tab's properties are updated (e.g. when you reload the tab, the url property is updated).

Clicking on a link that loads a different video into the current web-page (e.g. through AJAX) does not trigger an onUpdated event.

If you want to listen for changes in the web-page itself, you should look into MutationObserver.
For some examples on using a MutationObserver within a Chrome Extension you can take a look here and there.

Community
  • 1
  • 1
gkalpak
  • 47,844
  • 8
  • 105
  • 118