0

I've looked through a lot of questions and I can't find a solution that works well within my environment. This is done within Shopify, I have a product with variants. When a variant is changed, the URL is appended with a product ID which changes the product price dynamically (no reload).

I have an extra strip detecting when this change happens so I can so some extra stuff, and currently, it does detect it but it seems like wasted power the route I took with it.

$(document).ready(function() {
    setInterval(function() {
      checkURLchange(window.location.href);
    }, 10);

It happens every 10 ms so the change seems instant to the user (let's say I appended a new picture to the page or something on variant change).

It would be more much effective if I could just save the state of the URL and check if it has changed, but again Im unaware to approach this.

The typical hashChanged event for window does not work in this situation because the url change does not use hashes (Shopify), instead it looks something like this:

?variant=99390743207991

or

?variant=13390743202341

What about popstate (history change)?

Unfortunately, this does not seem to work either. As popstate or the answer suggested here.

Feel free to see the solution being tested in my chaotic staging environment: https://ti560ye2q51lxyvj-11502512.shopifypreview.com/products/the-wg-m1-grill-kit

Robolisk
  • 1,682
  • 5
  • 22
  • 49
  • You can use the [`popstate`](https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event) event to detect changes in URL history. – Rory McCrossan Oct 21 '19 at 14:56
  • Have you tried [this](https://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate)? – User863 Oct 21 '19 at 14:58
  • Possible duplicate of [How to get notified about changes of the history via history.pushState?](https://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate) – freedomn-m Oct 21 '19 at 15:03

1 Answers1

1

Listen to window for popstate.

window.addEventListener('popstate', () => {
    /* do something */
})

You can test this by adding a console log to it and changing the hash with window.location.hash = 'somehash'.

Jay Kariesch
  • 1,392
  • 7
  • 13
  • Sadly this solution does not work for me as well. I added in the event listener and when I changed the variant (in turn appending the URL) the event never trigged, but explicitly setting the hash within the console to test does trigger it. When this URL gets appended nothing gets reloaded. I was under the impression popstate/histroy is effective for navigation (new pages/hash etc). – Robolisk Oct 21 '19 at 15:19