Skip to content

Commit 7e2e8cd

Browse files
committed
doc: matching SPA
1 parent 6ea502f commit 7e2e8cd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

content/api/matching.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,37 @@ Here is the long version:
9292
- If neither `@match` nor `@include` rule is defined, the script is assumed to match.
9393

9494
![match.png](match.png)
95+
96+
Matching SPA sites like fb, github, twitter, youtube
97+
---
98+
99+
Userscript extensions use the native behavior of the browser - it runs scripts defined by extensions only during the standard "hard" navigation, not during "soft" navigation via history.pushState or replaceState or #hash changes used by many modern [SPA sites](https://en.wikipedia.org/wiki/Single-page_application).
100+
101+
You can verify the type by opening devtools network log, then navigate in this tab (e.g. click a link) and look at the type of the request for this navigation: a `Document` (Chrome) or `HTML` (Firefox) means "hard" navigation i.e. the browser creates a new environment for the page and loads its HTML from the server including its scripts and userscripts from extensions.
102+
103+
**1. Run your userscript on the entire SPA site:**
104+
```js
105+
// @match *://www.youtube.com/*
106+
```
107+
**2. Then watch for changes** either using [vm-url](https://github.com/violentmonkey/vm-url) or manually:
108+
109+
```js
110+
onUrlChange();
111+
112+
if (self.navigation) {
113+
navigation.addEventListener('navigatesuccess', onUrlChange);
114+
} else {
115+
let u = location.href;
116+
new MutationObserver(() => u !== (u = location.href) && onUrlChange())
117+
.observe(document, {subtree: true, childList: true});
118+
}
119+
120+
function onUrlChange() {
121+
if (!location.pathname.startsWith('/watch')) {
122+
// deactivate();
123+
return;
124+
}
125+
console.log('processing', location.href);
126+
// activate();
127+
}
128+
```

0 commit comments

Comments
 (0)