2

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()
Swangie
  • 175
  • 8

1 Answers1

1

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();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320