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

怎甘沉沦 提交于 2021-01-28 04:09:19

问题


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()

回答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();


来源:https://stackoverflow.com/questions/65545401/how-do-i-make-my-userscript-execute-code-in-isolated-sandbox-and-unsafewindow-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!