You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Greasemonkey 4中跨域iframe内运行用户脚本?

在Greasemonkey 4.11中为跨域iframe运行用户脚本的问题

场景与需求

第三方网站domain1.com的页面嵌入了来自domain2.com的跨域iframe,代码如下:

<html>
  ...
    <iframe src="domain2.com/?...">...</iframe>
  ...
</html>

需要仅在该iframe内执行用户脚本,无需iframe与嵌入页面进行通信。当前使用环境为Firefox 103.0 + Greasemonkey 4.11。

未理清的核心问题

查阅相关内容后,仍无法明确以下几点与现有问题的对应逻辑:

  • iframe同源/跨域状态对脚本执行的影响
  • iframe与嵌入页面的交互限制边界
  • iframe加载时间如何影响脚本触发时机
  • Greasemonkey版本差异(≥4与<4)带来的脚本适配规则变化

尝试过的无效方案

方案1:适配Greasemonkey <4的脚本(其他管理器有效,Greasemonkey4中iframe分支不触发)

该脚本在Chrome的Tampermonkey、Firefox的Violentmonkey中可正常触发iframe分支,但在Greasemonkey 4中仅主页面分支能执行:

// ==UserScript==
// @name     foo1
// @version  1
// @grant    none
// @match    https://domain1.com
// @match    https://domain2.com/*
// ==/UserScript==

setInterval(() => {
  if (window.top === window.self) {
    // 正常执行
    console.log("top")
  } else {
    // 无法触发
    console.log("iframe")
  }
}, 3000)

方案2:据称适配Greasemonkey ≥4的脚本(因跨域限制报错)

尝试通过监听iframe元素来操作,但受同源策略限制,无法访问iframe的document对象:

// ==UserScript==
// @name     foo2
// @version  1
// @grant    none
// @match    https://domain1.com
// @match    https://domain2.com/*
// @require https://git.io/waitForKeyElements.js
// ==/UserScript==

waitForKeyElements("iframe", function(elem) {
  setInterval(() => {
    // 可正常输出
    console.log(elem.contentWindow)
    try {
      // 抛出SecurityError:跨域对象的document属性访问被拒绝
      console.log(elem.contentWindow.document)
    } catch (e) {
      console.log("ERROR " + e);
    }
  }, 3000)
});

内容的提问来源于stack exchange,提问作者Marco Eckstein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:06:30