0

I'm currently working on a Chrome Extension. I did two ways to monitor URL changes:

  1. Use a mutation Observer to observe all sub-elements changing;
  2. Check if the window.location.href is equal to the old href.

The first one is working, but it may cost too many calls and not be easy to extend in the future. The second one is simple, the code is:

var currentPage = window.location.href;
    setInterval(() => {
        if (currentPage != window.location.href) {
            currentPage = window.location.href;
            $(function() {
                myFunction(); //append some buttons inside the HTML
            });
        }
    }, 500);

But this doesn't work, since when it finds that the currentPage has changed, the myFunction will append buttons in the old HTML pages immediately since the new page is not reloaded, but the old one is.

I'm wondering if there are any ways to just change a little bit in this code and make it work, so that the buttons will append to the current page correctly.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
  • 1
    Search your title - for example this https://stackoverflow.com/questions/34957319/how-to-listen-for-url-change-with-chrome-extension – mplungjan Jun 27 '17 at 15:31

1 Answers1

0

Try the DOMContentLoaded event to execute functions after DOM loads.

document.addEventListener('DOMContentLoaded', function(){
//your code for after the page is loaded
});
CoursesWeb
  • 4,179
  • 3
  • 21
  • 27