如何让我的用户脚本在隔离沙箱和 unsafeWindow 中执行代码?

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

对于用户脚本中的大部分代码,我需要对执行脚本的网站使用 unsafeWindow。我通过使用 // @grant unsafeWindow 来做到这一点。但是,我的某些代码无法使用 unsafeWindow 执行,需要在 Tampermonkey 的隔离沙箱中执行 运行。我怎么能做到这一点?像这样的东西可以工作:

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>标签中,例如:

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