使用postMessage从父级调用iFrame中的javascript函数
下面代码的目的是调用#pm框架内的函数window.name1.function1(val),并将“someVal”作为参数 但是,当我尝试调用window.location.assign(“someUrl”)by使用postMessage从父级调用iFrame中的javascript函数,javascript,jquery,iframe,postmessage,Javascript,Jquery,Iframe,Postmessage,下面代码的目的是调用#pm框架内的函数window.name1.function1(val),并将“someVal”作为参数 但是,当我尝试调用window.location.assign(“someUrl”)byExecFcn([“location”,“assign”],“someUrl”,…) 当iframe尝试调用函数时,我得到一个“非法调用”错误。 我假设这与我正在创建函数的一个副本,并且在创建过程中丢失了一些必要的信息有关?但范围似乎没有改变,所以我不确定问题出在哪里 父文档 var
ExecFcn([“location”,“assign”],“someUrl”,…)
当iframe尝试调用函数时,我得到一个“非法调用”错误。
我假设这与我正在创建函数的一个副本,并且在创建过程中丢失了一些必要的信息有关?但范围似乎没有改变,所以我不确定问题出在哪里
父文档
var fcnReference = ["name1","function1"]; // define the function reference
ExecFcn(fcnReference, "someVal", function (data) {
// do something
});
...
function ExecFcn(pNames, pValue, pCallback) {
// setup the data to pass to the child iframe
var eventData = {
eventId: "windowFcn",
data: {
names: pNames,
param: pValue,
callback: pCallback
}
};
// post the data to the frame
PostEvent(eventData);
}
function PostEvent(e) {
iframe = document.getElementById('pm-frame');
iframe.contentWindow.postMessage(e, "*");
}
IFRAME:
window.addEventListener('message', function (e) { // message received
var evt = e.data;
switch(evt.eventId)
{
case "windowFcn": // if the eventId is a request to run a function
// build the reference
// ["name1","fcn1"] => window.name1.fcn1()
var fcn = window;
$(evt.data.names).each(function(i,p){
fcn = fcn[p];
});
var op = fcn(param); // throws illegal invocation
postData = {
eventId: "windowFcn",
data: {
callback: evt.data.callback
output: op
}
}
parent.postMessage(postData,"*");
break;
}