gpt4 book ai didi

javascript - 如何通过 postMessage 执行函数

转载 作者:可可西里 更新时间:2023-11-01 02:30:32 26 4
gpt4 key购买 nike

我在 iframe 中有这段代码:

window.addEventListener('message', function(e){

if(e.data == 'test')
console.log(e);

}, false);

父文档中的这个:

$('#the_iframe').get(0).contentWindow.postMessage('test', 'http://localhost/');

因此父文档向 iframe 发送了一条“测试”消息并且它起作用了。

但是我怎样才能在父文档中定义一个函数,并以某种方式通过 postMessage 将这个函数发送到 iframe,它会在本地执行该函数?

该函数像这样对文档进行一些更改:

var func = function(){
$("#some_div").addClass('sss');
}

(#some_div存在于iframe中,不是父文档)

最佳答案

没有什么可以阻止您将字符串化函数作为消息后事件数据传递。实现是微不足道的,对于像

这样的任何函数声明
function doSomething(){
alert("hello world!");
}

你可以encodeURI它的字符串解释:

console.log(encodeURI(doSomething.toString()));
//function%20doSomething()%20%7B%0A%20%20%20%20alert(%22hello%20world!%22);%0A%7D

然后它可以作为闭包的一部分执行 - 一些不太像

eval('('+decodeURI(strCallback)+')();');

有一个 fiddle'd proof of concept 没有跨框架架构 - 我会看看我是否可以组合一个 postMessage 版本,但是使用 jsfiddle 来托管并不是一件容易的事

更新

正如所 promise 的那样,一个完整的模型可以正常工作(下面的链接)。通过正确的 event.origin 检查,这将是足够难以渗透的,但我知道我们的安全团队永远不会让 eval 像这样进入生产:)

考虑到这个选项,我建议在两个页面之间对功能进行规范化,这样只需要传递一个参数消息(即传递参数而不是函数);但是,在某些情况下,这肯定是首选方法。

父代码:

document.domain = "fiddle.jshell.net";//sync the domains
window.addEventListener("message", receiveMessage, false);//set up the listener

function receiveMessage(e) {
try {
//attempt to deserialize function and execute as closure
eval('(' + decodeURI(e.data) + ')();');
} catch(e) {}
}

iframe代码:

document.domain = "fiddle.jshell.net";//sync the domains
window.addEventListener("message", receiveMessage, false);//set up the listener

function receiveMessage(e) {
//"reply" with a serialized function
e.source.postMessage(serializeFunction(doSomething), "http://fiddle.jshell.net");
}

function serializeFunction(f) {
return encodeURI(f.toString());
}

function doSomething() {
alert("hello world!");
}

原型(prototype)模型:parent codeiframe code .

关于javascript - 如何通过 postMessage 执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11005223/

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