【问题标题】:How to run script only if div:contains in an iFrame - Greasemonkey仅当 div:包含在 iFrame 中时如何运行脚本 - Greasemonkey
【发布时间】:2021-11-24 01:26:14
【问题描述】:

假设我们在 iFrame 中有这段代码。我很确定 iFrame 来自同一个域,我认为这很重要。

<div id="10">You become 1 best coder</div>

我想要一个 Greasemonkey 脚本,它仅在“div id=10”和文本(或部分文本)都为真时运行脚本。

我试过了:

// ==UserScript==
// @name        Script
// @include     https://www.somesite.com/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

var intv = setInterval(function() {
    
    const sp = document.querySelector('#10'); // find id (some)
if (sp && sp.textContent === 'You become 1 best coder') {

alert('Hello world!');
    
    }

      }, 5000);

这适用于具有常规内容的常规页面。但是,当我需要脚本识别以便在 iFrame 中运行加载的内容时,脚本不会运行。

以下是 iFrame 代码示例:

<iframe src="something.php?text=M0000310y100g190e500A78014607601&amp;lalala=tT6&amp;ctrl=032a4c3342e76e97ea21821a5c5f800e&amp;mamama=c2ed5535532cc20aef064db2b4" width="100%" height="100%" frameborder="0"></iframe>

我假设 iFrame 来自同一个域,因为如果它来自不同的域,我认为 src="" 会有所不同...

有人可以帮忙吗?谢谢

【问题讨论】:

    标签: javascript iframe greasemonkey


    【解决方案1】:

    首先您需要获取iframe。如果这是唯一的,那么您可以尝试....

    注意:根据评论更新

    // ==UserScript==
    // @name        Script
    // @include     https://www.somesite.com/*
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
    // @grant       GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    
    const intv = setInterval(function() {
      const iframe = document.querySelector('iframe[src*="something.php"]');
      const sp = iframe && iframe.contentWindow.document.body.querySelector('#10'); // find id (some)
      if (sp && sp.textContent === 'You become 1 best coder') {
        alert('Hello world!');
      }
    }, 5000);
    

    更新

    iframe 内容也是文档。如果代码不需要与父框架交互,您可以将用户脚本注入目标 iframe 文档并在那里运行。

    【讨论】:

    • 我在 Firefox 55.0.2 和 74.0.1 上尝试过,但没有成功。我使用了检查元素,我的 div 位于 iframe>body>div 中。页面上还有其他 iFrame,但它们位于主 iframe 内。有什么想法吗?
    • 在 Firefox 55.0.2(这是我想使用脚本的地方)我在控制台中运行脚本 - const sp = document.querySelector('iframe')?.contentWindow.document .body.querySelector('#10'); if (sp && sp.textContent === '你成为 1 best coder') { alert('Hello world!'); } - 我得到了这个错误 - SyntaxError: expected expression, got '.'
    • 我说可选链是用于 FF74+ 的。如果有更多 iframe,那么您必须找到正确的 iframe。我会更新代码。
    • 是的,抱歉,我应该在开篇文章中提到我希望它适用于 Firefox 55。这是一条重要的信息,我完全忘记了。即使其他 iFrame 在一个主 iFrame 内,我是否必须找到正确的 iFrame?
    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多