Skip to content

[Feature] window.onurlchange #535

@cyfung1031

Description

@cyfung1031

https://www.tampermonkey.net/documentation.php?locale=en#api:window.onurlchange

greasyfork 查到的大约有 250 个脚本使用

例子: https://greasyfork.org/en/scripts/416957-no-youtube-chat


背景资料

现在其实有 navigation event
但firefox不支持

https://github.com/WICG/navigation-api

https://stackoverflow.com/questions/6390341/how-to-detect-if-url-has-changed-after-hash-in-javascript

Chrome 102+ (2022-05-24)


Fires when: The current entry in the navigation history changes, e.g., when using navigation.updateCurrentEntry().

Use case: Detect changes in the state of the current navigation entry (e.g., state restoration or update).


navigation.addEventListener('currententrychange', (event) => {
  console.log('Current entry changed:', event);
});

https://developer.mozilla.org/en-US/docs/Web/API/Navigation/currententrychange_event


Fires when: A navigation is initiated via a call to navigation.navigate().

Use case: Intercept navigation before it completes, possibly to cancel or modify it.

navigation.addEventListener('navigate', (event) => {
  console.log('Navigation started:', event);
  // event.intercept() can be used here
});

https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate_event


Fires when: A navigation attempt fails (e.g., due to an exception or a rejected promise).

Use case: Handle failed navigations gracefully.

navigation.addEventListener('navigateerror', (event) => {
  console.error('Navigation error:', event.error);
});

https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigateerror_event


Fires when: A navigation completes successfully.

Use case: Trigger logic after a new route is fully activated.

navigation.addEventListener('navigatesuccess', (event) => {
  console.log('Navigation successful to:', event.destination.url);
});

https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigatesuccess_event


所以还是做最白痴传统的?

做油猴最基本的urlchange

let oldUrl = location.href;
const f = () => {
  const newUrl = location.href;
  if (newUrl !== oldUrl) {
    oldUrl = newUrl;
    window.dispatchEvent(new CustomEvent("urlchange"));
  }
};

let cid = 0;
const g = () => {
  if (cid) {
    clearTimeout(cid);
    cid = 0;
  }
  f();
  Promise.resolve().then(f);
  cid = setTimeout(f, 50);
};

window.addEventListener("popstate", g);
window.addEventListener("hashchange", g);
// window.addEventListener("load", g); // 感觉不需要
// window.addEventListener("DOMContentLoaded", g); // 感觉不需要

const observer = new MutationObserver(() => {
  g();
});

observer.observe(document, {
  subtree: true,
  childList: true,
  attributes: true,
  characterData: true,
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    GM API支持一下TM/VM/FM的APIenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions