// ==UserScript==
// @name New Userscript
// @match http://main-domain.something
// @match *.example.com/*
// ==/UserScript==
(function() {
'use strict';
if (window.top === window.self) {
// Here we are at the top window and we setup our message event listener
}
else {
// Here we get inside the iframes.
// We can address and check each iframe url with document.domain
}
})();
window.top.postMessage({
// data object we send to the top window
}, "*");
我创建了一个试用这个的演示,它运行得很好。我的首页窗口网址是http://zikro.gr/dbg/gm/iframes/main.php ,子域名就像http://subdomain1.zikro.gr/ 。顶部窗口 HTML 与我的 iframe 网址和 GM 脚本完全相同:
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://zikro.gr/dbg/gm/iframes/main.php
// @match *.zikro.gr/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
if (window.top === window.self) {
// Here we are at the top window and we setup our message event listener
document.body.style.backgroundColor = "#f00"; // Just a UI change to identify the top window
window.addEventListener("message", function(event) {
window.console.log("This is data from '" + event.data.title +
"'; with message '" + event.data.message +
"'; with data '" + event.data.data +"'" +
"'; from domain '" + event.data.domain + "'");
}, false);
}
else {
// Here we get inside the iframes.
// We can address and check each iframe url with document.domain
document.body.style.backgroundColor = "#0f0"; // Just a UI change to identify the iframe window
// We change something inside the iframe
var dataDiv = document.getElementsByTagName('div')[0];
dataDiv.innerHTML += " with a change!";
// And we post a message to the top window with all the data we want inside an object
window.top.postMessage({
title: document.title,
domain: document.domain,
message: "Hello from, iframe - " + document.title,
data: dataDiv.innerText
}, "*");
}
})();
我认为唯一
window.postMessage()
方法是使用window.postMessage()
方法将包含 iframe 数据的消息发送到顶部窗口。 要在 Greasemonkey 脚本中捕获每个 iframe,请参阅将 Greasemonkey 用户应用于 iframe 的 Brock Adams 回答 ? ; 你必须像这样使用 GM@match
指令:要么
然后,您可以检查当前窗口是否是顶部窗口,和 / 或检查
document.domain
以标识 iframe:我们需要将
"message"
的事件挂钩到顶部窗口,该窗口将处理从 iframe 接收的每条消息以及数据:我们可以使用
document.domain
识别 iframe; 对 iframe 元素进行任何操作; 检索我们想要的所有数据并将消息发送到顶部窗口:我创建了一个试用这个的演示,它运行得很好。 我的首页窗口网址是
http://zikro.gr/dbg/gm/iframes/main.php
,子域名就像http://subdomain1.zikro.gr/
。 顶部窗口 HTML 与我的 iframe 网址和 GM 脚本完全相同:并且为那些没有安装 Greasemonkey / Tampermoney 的人进行屏幕截图测试:
**PS:在 iframe 标签中直接添加元素是无效的,如下所示:**
https://stackoom.com/question/35lHv/%E7%94%A8%E6%88%B7%E8%84%9A%E6%9C%AC%E7%BB%95%E8%BF%87%E5%90%8C%E6%BA%90%E7%AD%96%E7%95%A5%E4%BB%A5%E8%AE%BF%E9%97%AE%E5%B5%8C%E5%A5%97%E7%9A%84iframe