简体   繁体   中英

How do I make my userscript execute code in isolated sandbox and unsafeWindow too?

For most of my code in my userscript, I'm need to use unsafeWindow for the websites my script executes on. I do this by using // @grant unsafeWindow . However, some of my code cannot be executed with unsafeWindow and needs to run in Tampermonkey's isolated sandbox. How would I be able to do this? Something like this could work:

function disableUnsafeWindow() {
    // Disable UnsafeWindow
}

function enableUnsafeWindow() {
    // Enable unsafeWindow
}
function withUnsafeWindow() {
    enableUnsafeWindow()
    // Run the code using unsafeWindow
}

function withoutUnsafeWindow() {
    disableUnsafeWindow();
    // Remove unsafeWindow access and execute the code without unsafeWindow
}

withUnsafeWindow()
withoutUnsafeWindow()

Use the isolated sandbox with the privileged userscript functions by default. Then, for the code that requires use of the native page, you could insert the code into a <script> tag, eg:

 const fnToRunOnNativePage = () => { console.log('fnToRunOnNativePage'); }; const script = document.body.appendChild(document.createElement('script')); script.textContent = '(' + fnToRunOnNativePage.toString() + ')();'; // to use information inside the function that was retrieved elsewhere in the script, // pass arguments above script.remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM