-
Notifications
You must be signed in to change notification settings - Fork 11
/
yt_redirect.js
55 lines (46 loc) · 1.38 KB
/
yt_redirect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(() => {
const NO_REDIRECT_PARAM_KEY = 'hyperweb-d-r';
let lastUrl = location.href;
const tryRedirect = () => {
try {
const url = new URL(location.href);
url.searchParams.append(NO_REDIRECT_PARAM_KEY, '1');
history.replaceState({}, '', url.href);
window.location.href = url.href;
} catch {}
};
const run = () => {
const threshold = 150;
const testImage = "http://www.google.com/images/phd/px.gif";
const dummyImage = new Image();
const testLatency = (cb) => {
var tStart = new Date().getTime();
dummyImage.src = testImage;
dummyImage.onload = function() {
var tEnd = new Date().getTime();
cb(tEnd-tStart);
};
}
try {
const url = new URL(location.href);
const host = url.hostname;
const isTarget = [ 'm.youtube.com', 'www.youtube.com' ].some((h) => host.includes(h));
const shouldRedirect = isTarget && url.pathname.startsWith('/watch') && !url.searchParams.has(NO_REDIRECT_PARAM_KEY);
if (shouldRedirect) {
testLatency((avg) => {
if (avg <= threshold) {
tryRedirect();
}
});
}
} catch {}
};
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
run();
}
}).observe(document, { subtree: true, childList: true });
run();
})();