gpt4 book ai didi

javascript - 使用 postmessage 与 iframe 通信 - 错误在哪里?

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:22 25 4
gpt4 key购买 nike

我有一个 Greasemonkey 脚本,它应该向嵌入式 iframe 发送一个后置消息,在该 iframe 中,相同的脚本启动一个函数。我的注意力是发送一个简单的消息来触发 iframe 中的一个函数。该网站和 iframe 不在同一域中。我的js技术很差,找不到问题。

感谢阅读

// ==UserScript==
// @name Test
// @namespace
// @include domainA
// @include domainB
// @version 1
// @grant none
// ==/UserScript==

if ("domainA" === location.hostname)
{
if (window === top) // prevents the script from running twice on domain A
{
window.setTimeout(delay, 15000);
function delay()
{
console.log("Delay");
document.getElementsByTagName("Iframe")[0].contentWindow.postMessage('message', 'domainB'); //The issue is probably here
}
}
}
else // domain B
{
window.onmessage = function() // or here
{
console.log("Done"); // Didnt start
}
}

编辑:我正在使用 Firefox

最佳答案

我认为您无法在一个脚本中完成此操作。如果您创建两个脚本,它将起作用。确保每个脚本只包含一个域。

获取 iframe 并向其发送消息的第一个脚本:

// ==UserScript==
// @name Test
// @namespace
// @include domainA
// @version 1
// @grant none
// ==/UserScript==

if (window === top) // prevents the script from running twice on domain A
{
window.setTimeout(delay, 15000);
function delay()
{
console.log("Delay");
document.getElementsByTagName("Iframe")[0].contentWindow.postMessage('message', 'domainB'); //The issue is probably here
}
}

匹配 iframe 域并附加事件处理程序的第二个脚本:

// ==UserScript==
// @name Test IFrame
// @namespace
// @include domainB
// @version 1
// @grant none
// ==/UserScript==

if (window.addEventListener)
{
window.addEventListener("message", function (event)
{
console.log("Done");
}
}
else // IE8 or earlier
{
window.attachEvent("onmessage", function (event)
{
console.log("Done");
}
}

关于javascript - 使用 postmessage 与 iframe 通信 - 错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com