简体   繁体   English

从父级传递JavaScript变量到iframe

[英]Pass a javascript variable from parent to the iframe

I know we can pass a javascript variable from an iframe to the parent frame like this: 我知道我们可以将javascript变量从iframe传递到父框架,如下所示:

If the parent and iframe were both on the same domain, we can call a function of the parent window: 如果父级和iframe都在同一域中,则可以调用父级窗口的函数:

iframe code: iframe代码:

window.postMe = "postMe value here";
window.parent.myFunction(postMe);

In the parent window, we can define a function like this: 在父窗口中,我们可以定义如下函数:

function myFunction(postMe) {
    ((console&&console.log)||alert)("postMe= " + postMe);
}

And the code above logs the "postMe" value correctly. 上面的代码正确记录了“ postMe”值。

But my question is how to modify this code in order to pass "postMe" from parent to the iframe ? 但是我的问题是如何修改此代码 ,以便将“ postMe”从父级传递到iframe

If you want to continue using the myFunction on the parent, you can have the parent function accept a callback passed by the child: 如果要继续在父级上使用myFunction ,则可以让父级函数接受子级传递的回调:

window.postMe = "postMe value here";
window.parent.myFunction(postMe, (response) => {
  console.log(response);
});
function myFunction(postMe, callback) {
  const val = "postMe= " + postMe;

  // do something with val in parent:
  ((console&&console.log)||alert)(val);

  // do something with val in child:
  callback(val);
}

See here for a live demonstration (can't be embedded as a Stack Snippet due to sandboxing issues): 参见此处的现场演示(由于沙箱问题,无法作为堆栈片段嵌入):

https://jsfiddle.net/kc24onbq/ https://jsfiddle.net/kc24onbq/

For one-way communication from the parent to the child, access the contentWindow of the iframe from the parent: 对于从父级到子级的单向通信,请从父级访问iframe的contentWindow

// child
function childFn(val) {
  console.log(val);
}
// parent
iFrameElement.contentWindow.childFn('foo');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM