本文介绍了如何使我的用户脚本也在隔离的沙箱和unsafeWindow中执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的用户脚本中的大多数代码,我需要对执行脚本的网站使用 unsafeWindow .我通过使用//@grant unsafeWindow 来做到这一点.但是,我的某些代码无法用 unsafeWindow 执行,需要在Tampermonkey的隔离沙箱中运行.我将如何做到这一点?这样的事情可能会起作用:

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

推荐答案

默认情况下,将隔离的沙箱与特权用户脚本功能一起使用.然后,对于需要使用本机页面的代码,您可以将代码插入< script> 标记中,例如:

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

这篇关于如何使我的用户脚本也在隔离的沙箱和unsafeWindow中执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 17:17