如何仅在div:包含在iframe-grasemonkey中时运行脚本 [英] How to run script only if div:contains in an iFrame - Greasemonkey

查看:56
本文介绍了如何仅在div:包含在iframe-grasemonkey中时运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要一个仅当";div id=10";且文本(或部分文本)为真时才运行脚本的Gresemonkey脚本。

我尝试过:

// ==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=&q;&q;我想...

有人能帮忙吗?谢谢

推荐答案

首先需要获取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文档中插入用户脚本并在那里运行它。

这篇关于如何仅在div:包含在iframe-grasemonkey中时运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆