window.postMessage提示:家长沟通

    技术2022-07-11  116

    I wrote a super epic post a few months back about the window.postMessage API that's sweeping the nation.  window.postMessage allows you to send messages not only across frames (regular frame or iframe) but also across domains.  My post showed interaction from parent to child and back to the parent, but didn't detail passing messages from a child to a parent without the parent initializing the conversation.  Let me show you how you can initialize that conversation from child to parent

    几个月前,我写了一篇关于window.postMessage API的超级史诗文章,风靡全国。 window.postMessage使您不仅可以跨帧(常规帧或iframe)发送消息,还可以跨域发送消息。 我的帖子显示了父母与孩子之间以及与父母之间的互动,但是没有详细说明在父母未初始化对话的情况下将消息从孩子传递给父母的情况。 让我向您展示如何初始化从孩子到父母的对话

    JavaScript (The JavaScript)

    The parent object provides a reference to the main window from the child.  So if I have an iFrame and console the parent within it, the console will read:

    父对象从子对象提供对主窗口的引用。 因此,如果我有一个iFrame并在其中管理父级,则控制台将显示为:

    // Every two seconds.... setInterval(function() { // Send the message "Hello" to the parent window // ...if the domain is still "davidwalsh.name" parent.postMessage("Hello","https://davidwalsh.name"); },1000);

    Since we now have hold of the window, we can postMessage to it:

    由于我们现在拥有该窗口,因此可以向其发布消息:

    // Create IE + others compatible event handler var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; // Listen to message from child window eventer(messageEvent,function(e) { console.log('parent received message!: ',e.data); },false);

    The directive above triggers the iFrame to send a message to the parent window every 3 seconds.  No initial message from the main window needed!

    上面的指令会触发iFrame每3秒向父窗口发送一条消息。 不需要来自主窗口的初始消息!

    翻译自: https://davidwalsh.name/window-iframe

    Processed: 0.008, SQL: 9