0

Keep in mind I am very new to extensions/add ons.

I have the following function in my content.js script:

function getUpc() {
    var lotsOfData = document.getElementById("__NEXT_DATA__");
    lotsOfData = JSON.parse(lotsOfData.innerHTML);
    var upc = lotsOfData.props.pageProps.initialData.data.product.upc;
    return upc;
}

console.log("UPC: " + getUpc());

This function grabs the upc data from a walmart product. Now this function works great if I press the refresh button while looking at a product, but wont load when I search said product in walmart. It seems walmart is using AJAX or something to dynamically update the page and updates the URL when using the search feature. So I need some way to detect a URL/URI change and re-run my function.

Ive tried some solutions like a background script that listens for the 'popstate' or a change in the history, however to no avail. I just need some way to detect a dynamic change in the URL and run my function when it does.

Max
  • 77
  • 6
  • Use [navigation.onnavigate](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate_event) event in the content script. Note though, the site may keep the old contents of the element, in which case you'll need to intercept the AJAX response, [example](/q/8939467). – wOxxOm Apr 01 '23 at 18:58
  • @wOxxOm It appears that the navigation event is [not compatible with firefox](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate_event#browser_compatibility), otherwise that would be perfect – Max Apr 01 '23 at 19:21
  • 1
    Oops. Well, maybe use MutationObserver, see [this answer](https://stackoverflow.com/a/39508954). – wOxxOm Apr 01 '23 at 19:42

1 Answers1

0

Thanks @wOxxOm for finding the answer :) Heres how to do this:

let previousUrl = '';
let observer = new MutationObserver(function (mutations) {
    if (location.href !== previousUrl) {
        previousUrl = location.href;
        console.log(`URL data changed to ${location.href}`);
        // your code here
    }
});

const config = {attributes: true, childList: true, subtree: true};
observer.observe(document, config);

This will run your code anytime the url changes

Max
  • 77
  • 6