Chrome extension run content script on ajax change

怎甘沉沦 提交于 2019-12-30 05:13:17

问题


I have a chrome extension which makes some changes on the site (editing comments).

After recent changes on the site (site is not mine) - the comment block loads using ajax (before it was simple post request with the whole page reload).

Now if I load the page first time - content script works, but when I go to next page, say page #2 - the comments are added using ajax and the extension script is not run anymore. So the comments are not changed the way I want.

Is there any simple way to listen to page changes DOM and apply extension script again?

in manifest file I have:

{
  "name": "Name",
  "version": "1.0",
  "description": "Description",
  "icons": {"16":"16.png",
            "48":"48.png",
            "32":"32.png",
            "128":"128.png"},
  "browser_action": {
    "default_title": "Default title",
    "default_icon": "48.png",
    "popup": "popup.html"
  },
  "permissions": [
    "tabs",
    "http://www.site.com/*",
    "notifications",
    "unlimitedStorage"
  ],

  "options_page": "options.html",
  "background_page": "background.html",

  "content_scripts": [
                {
                    "matches": ["http://www.site.com/*","https://www.site.com/*"],
                    "js": ["jquery-1.7.1.min.js","content.js"],
                    "run_at": "document_end"
                }]
}

回答1:


You could add a listener on the event called DOMSubtreeModified. Bind a function to it, and it gets called whenever there's a change.

In jQuery:

$('#ContentContainer').bind('DOMSubtreeModified',modifyComments);

UPDATE:

In case the event is firing multiple times, delete the event binding during the first time, and after a certain timeout, you can call modifyComments and rebind the event.

function DOMModificationHandler(){
    $(this).unbind('DOMSubtreeModified.event1');
    setTimeout(function(){
        modifyComments();
        $('#ContentContainer').bind('DOMSubtreeModified.event1',DOMModificationHandler);
    },1000);
}

//after document-load
$('#ContentContainer').bind('DOMSubtreeModified.event1',DOMModificationHandler);


来源:https://stackoverflow.com/questions/11084819/chrome-extension-run-content-script-on-ajax-change

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