Content Script is not working in chrome extension

耗尽温柔 提交于 2020-01-17 03:03:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20379473/content-script-is-not-working-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!