I'm trying to execute a content script for a certain site (inject a button or change the link) however I would like to do this as the user browses the website.
The problem is that the web page is built dynamically with ajax requests as the user browses.
I had solved this earlier in an extension I had written by actually injecting my javascript into the web page.
I was wondering whether there is a better alternative of just being able to register for an ajaxComplete event or something similar in my content script so that I can re-execute.
I can do the following:
function listener()
{
console.debug("listener fired.");
}
document.addEventListener("DOMSubtreeModified", listener, false);
However that fires way too many times during one page load.
There is no ajax listener that I am aware of, but it wouldn't help much anyway as you need to catch when page is modified, not ajax request is sent/received (page modification usually happens later and can be not tied to ajax request at all).
DOMSubtreeModified
is the right way to go, just implement some protection from too frequent calls:This way it would trigger
listener
if there was no other events within 500ms.The best answer I found was a bit interesting and involved a bit of message passing in between the content scripts and the background.html file.
I'll post the code then explain:
Background.html
content_script.js
You want to solve updating or re-executing the script on DOM changes. Luckily the DOM changes involved a URL change (although it was AJAX DOM changes to update the page). The URL change however fires a onUpdated event. However every tab is firing these "events" and we want to make sure we only care about the one in which we have matched our content scripts too (you can specify a match in the manifest!).
By passing a messgae to the content_script being executed in the current tab, we are asking "Are you my content script? If so, please re-start."