Chrome extension: how to reload / reload script content on Ajax request

I am trying to execute script content for a specific site (enter a button or change a link), but I would like to do this when a user browses a website.

The problem is that the webpage is dynamically created using ajax requests when the user browses.

I solved this earlier in the extension that I wrote, actually injecting my javascript into the webpage.

I was wondering if there is a better alternative to simple registration for the ajaxComplete event or something similar in my script content so that I can re-execute.

I can do the following:

function listener() { console.debug("listener fired."); } document.addEventListener("DOMSubtreeModified", listener, false); 

However, this works too many times when loading a single page.

+6
source share
2 answers

There is no ajax listener that I know of, but that still will not help, since you need to catch when the page will be changed and the ajax request will not be sent / received (the page change usually happens later and cannot be tied to the ajax request at all).

DOMSubtreeModified is the right way, just do some protection against too frequent calls:

 function listener() { console.debug("listener fired."); } var timeout = null; document.addEventListener("DOMSubtreeModified", function() { if(timeout) { clearTimeout(timeout); } timeout = setTimeout(listener, 500); }, false); 

Thus, this will call a listener if there are no other events within 500 ms.

+7
source

The best answer I found was a bit interesting and included a message passing between the content scripts and the background.html file.

I will send the code and explain:

Background.html

  function updatePageAction(tabId) { chrome.tabs.sendRequest(tabId, {is_content_script: true}, function(response) { if (response.is_content_script) chrome.pageAction.show(tabId); }); }; chrome.tabs.onUpdated.addListener(function(tabId, change, tab) { if (change.status == "complete") { updatePageAction(tabId); } }); 

content_script.js

 // The background page is asking us to find an address on the page. if (window == top) { chrome.extension.onRequest.addListener(function(req, sender, sendResponse) { if (req.is_content_script) start_content_script(); sendResponse({is_content_script: true}); }); }; 

You want to decide whether to update or re-execute the DOM change script. Fortunately, DOM changes included a URL change (although there were AJAX DOM changes to refresh the page). However, changing the URL raises the onUpdated event. However, each tab fires these β€œevents”, and we want to make sure that we only care about where we also map our content scripts (you can specify a match in the manifest!).

Passing the messgae to the content_script executed on the current tab, we ask: "Are you my content script? If so, please restart it."

+4
source

Source: https://habr.com/ru/post/896742/


All Articles