-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathclose-window.js
100 lines (90 loc) · 2.76 KB
/
close-window.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { hit, toRegExp, logMessage } from '../helpers';
/**
* @scriptlet close-window
*
* @description
* Closes the browser tab immediately.
*
* > `window.close()` usage is restricted in the Chrome browser.
* > In this case tab will only be closed when using AdGuard Browser extension.
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('close-window'[, path])
* ```
*
* - `path` — optional, string or regular expression
* matching the current location's path: `window.location.pathname` + `window.location.search`.
* Defaults to execute on every page.
*
* ### Examples
*
* ```adblock
* ! closes any example.org tab
* example.org#%#//scriptlet('close-window')
*
* ! closes specific example.org tab
* example.org#%#//scriptlet('close-window', '/example-page.html')
* ```
*
* @added v1.5.0.
*/
export function forceWindowClose(source, path = '') {
// https://github.com/AdguardTeam/Scriptlets/issues/158#issuecomment-993423036
if (typeof window.close !== 'function') {
const message = 'window.close() is not a function so \'close-window\' scriptlet is unavailable';
logMessage(source, message);
return;
}
const closeImmediately = () => {
try {
hit(source);
window.close();
} catch (e) {
// log the error if window closing is impossible
// https://developer.mozilla.org/en-US/docs/Web/API/Window/close
logMessage(source, e);
}
};
const closeByExtension = () => {
const extCall = () => {
dispatchEvent(new Event('adguard:scriptlet-close-window'));
};
window.addEventListener('adguard:subscribed-to-close-window', extCall, { once: true });
setTimeout(() => {
window.removeEventListener('adguard:subscribed-to-close-window', extCall, { once: true });
}, 5000);
};
const shouldClose = () => {
if (path === '') {
return true;
}
const pathRegexp = toRegExp(path);
const currentPath = `${window.location.pathname}${window.location.search}`;
return pathRegexp.test(currentPath);
};
if (shouldClose()) {
closeImmediately();
if (navigator.userAgent.includes('Chrome')) {
closeByExtension();
}
}
}
export const forceWindowCloseNames = [
'close-window',
// aliases are needed for matching the related scriptlet converted into our syntax
'window-close-if.js',
'ubo-window-close-if.js',
'ubo-window-close-if',
'close-window.js',
'ubo-close-window.js',
'ubo-close-window',
];
// eslint-disable-next-line prefer-destructuring
forceWindowClose.primaryName = forceWindowCloseNames[0];
forceWindowClose.injections = [
hit,
toRegExp,
logMessage,
];