refactor: get sandbox window using GM APIs
This commit is contained in:
parent
ffa8683dbe
commit
334b452fcc
3 changed files with 12 additions and 0 deletions
|
@ -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
|
||||
|
||||
|
|
|
@ -14,5 +14,6 @@
|
|||
// @copyright Copyright (c) 2019-2020 Xmader
|
||||
// @grant unsafeWindow
|
||||
// @grant GM.registerMenuCommand
|
||||
// @grant GM.addElement
|
||||
// @run-at document-start
|
||||
// ==/UserScript==
|
||||
|
|
|
@ -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?
|
||||
|
|
Loading…
Reference in a new issue