有没有办法通过 Greasemonkey 仅在命名帧(而不是所有帧)中运行我的 JS 代码

Is there a way to run my JS code just in a named frame (instead of all frames) through Greasemonkey?

本文关键字:代码 JS 我的 运行 Greasemonkey 有没有      更新时间:2023-09-26

假设我有一个基于框架的网页,它看起来像这样:

+-------------+---------------------------------------------------------+
|             |           header                                        |
|             +---------------------------------------------------------+
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |           main                                          |
| menu        |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             |                                                         |
|             +---------------------------------------------------------+
|             |           footer                                        |
+-------------+---------------------------------------------------------+

如您所见,有一个名为 main 的框架。当用户单击menu框架中的菜单时,任何页面(任何 URL)都可以加载到main框架中。现在我想要的是只在main框架中加载的页面中运行一段代码。正如我所描述的,将在main框架中加载的页面没有 URL 模式,因此我无法在greasemonkey脚本中指定模式。有没有办法做到这一点?

谢谢。

这个问题不清楚。 如果你的意思是一个老式的(在HTML5中已经过时的)框架集,比如:

<frameset ...>
    <frame name="header" src="header.htm"           ></frame>
    <frame name="menu"   src="menu.htm"             ></frame>
    <frame name="main"   src="ANY_DOMAIN/page.htm"  ></frame>
    <frame name="footer" src="footer.htm"           ></frame>
</frameset>

,然后您必须将 Greasemonkey 脚本设置为在"主"框架中可能打开的所有可能页面上触发。

这里有一种方法可以做到这一点:

// ==UserScript==
// @name     _Fire on any page, but only when it is the frame named "main"
// @include  *
// ==/UserScript==
//-- Run in (i)framed page only, not in parent page.
if (window.top != window.self) {
    if (window.name == "main") {
        // PLACE YOUR DESIRED CODE HERE.
    }
}

重要:

  1. 仅将@include *用作最后的手段。 尽可能调整@include@exclude@match语句,使其仅在您希望加载到名为"main"的框架中的页面上运行。
  2. 如果这些帧都是同一个域,那么您有更多的选择。 您可以只运行 om 框架集页面,并根据需要将代码注入框架。 为此打开一个新问题。
  3. 在 Firefox 中使用 4.01 DOCTYPE 版本进行了测试。其他浏览器和HTML5可能不同或不可能。