M
M
Minat0_2020-09-23 00:05:31
JavaScript
Minat0_, 2020-09-23 00:05:31

How to add button using userscript when changing url?

Hello!
You need to add a button when changing the URL, he came up with only this code:

poke
let currentURL = window.location.href;

setInterval(function() {
  if(currentURL !== window.location.href) {
    if (window.location.pathname.split("/")[1] !== "" && window.location.pathname.split("/")[1] === "animes" && document.readyState === "complete") addButton();
  currentURL = window.location.href;
}, 1000);

function addButton() {
  if (document.querySelector('.slPlayFreePlayButton')) return;
    
  const id = window.location.pathname.split("/")[2].split('-')[0],
         a = document.createElement("a");
    
  a.classList.add('slPlayFreePlayButton');
  a.href = "https://example" + id + "/1";
  a.innerText = "Смотреть онлайн на Shikimøri Live";
  a.style.cssText = "padding: 1em; background-color: black; color: white; border-radius: 0.5em; display: block; margin: 0.5em 0";
  document.querySelector(".c-info-right").appendChild(a);
  }



The whole problem is that for some reason I have not seen, it happens that the button disappears, then suddenly two buttons appear, and then they disappear. I would be very happy with a clear explanation.

And another question: can userscript load itself on a dynamic web application to specific URLs, without reloading the page, for example, through directives?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Chipekwe, 2020-09-23
@zhenyavka

There is an event popstateto track the URL change.
To track changes in dynamic content, there is a MutationObserver.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question