【问题标题】:How do I make my userscript execute code in isolated sandbox and unsafeWindow too?如何让我的用户脚本在隔离沙箱和 unsafeWindow 中执行代码?
【发布时间】:2021-01-03 00:01:02
【问题描述】:

对于我的用户脚本中的大部分代码,我需要在我的脚本执行的网站上使用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()

【问题讨论】:

    标签: javascript function sandbox execution userscripts


    【解决方案1】:

    默认情况下使用具有特权用户脚本功能的隔离沙箱。然后,对于需要使用原生页面的代码,可以将代码插入到<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();

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 2010-09-24
      • 2016-07-06
      相关资源
      最近更新 更多