refactor: get sandbox window using GM APIs

This commit is contained in:
Xmader 2020-12-06 01:36:35 -05:00
parent ffa8683dbe
commit 334b452fcc
No known key found for this signature in database
GPG Key ID: A20B97FB9EB730E4
3 changed files with 12 additions and 0 deletions

View File

@ -8,6 +8,9 @@ declare const GM: {
/** https://www.tampermonkey.net/documentation.php#GM_registerMenuCommand */
registerMenuCommand (name: string, fn: () => any, accessKey?: string): Promise<number>;
/** https://github.com/Tampermonkey/tampermonkey/issues/881#issuecomment-639705679 */
addElement<K extends keyof HTMLElementTagNameMap> (tagName: K, properties: Record<string, any>): Promise<HTMLElementTagNameMap[K]>;
}
export const _GM = GM

View File

@ -14,5 +14,6 @@
// @copyright Copyright (c) 2019-2020 Xmader
// @grant unsafeWindow
// @grant GM.registerMenuCommand
// @grant GM.addElement
// @run-at document-start
// ==/UserScript==

View File

@ -1,5 +1,6 @@
import isNodeJs from 'detect-node'
import { isGmAvailable, _GM } from './gm'
export const escapeFilename = (s: string): string => {
return s.replace(/[\s<>:{}"/\\|?*~.\0\cA-\cZ]+/g, '_')
@ -60,6 +61,13 @@ export const useTimeout = async <T> (promise: T | Promise<T>, ms: number): Promi
export const getSandboxWindowAsync = async (targetEl: Element | undefined = undefined): Promise<Window> => {
if (typeof document === 'undefined') return {} as any as Window
if (isGmAvailable('addElement')) {
// create iframe using GM_addElement API
const iframe = await _GM.addElement('iframe', {})
iframe.style.display = 'none'
return iframe.contentWindow as Window
}
if (!targetEl) {
return new Promise((resolve) => {
// You need ads in your pages, right?