postMessage 函数重复运行而没有发送消息

postMessage Function runs repeatedly without a message being sent

我有一个带有表单的 iframe,在那个 iframe 中我有以下内容:

// Send a message to the parent window  
window.parent.postMessage({
    event: 'submit'
}, '*');

以上应该在提交表单时向父 window 发送消息。

在父 window 我有以下内容:

function receiveMessage(event) {

    var origin = event.origin;

    if (origin !== 'https://iframe.domain') {
        return;
    } else {    
        console.log('Submitted!');
    }
}

window.addEventListener('message', receiveMessage, false);

我似乎遇到的问题是父 window 上的代码正在立即执行,而没有从正在提交的 iframe 表单发送消息。它还在一遍又一遍地执行。只要我让它 运行.

,它就会一遍又一遍地在控制台中记录 "Submitted!"

这个函数运行怎么会在没有提交表单的情况下发送函数,为什么运行一遍又一遍

您需要检查是否收到了正确的消息。

function receiveMessage(event) {
  if (event.origin !== 'https://iframe.domain') {
    return;
  } else if (event.data.event && event.data.event === 'submit') {    
     console.log('Submitted!');
  }
}

window.addEventListener('message', receiveMessage, false);

我觉得你收到这么多消息很奇怪,我建议添加一些代码将它们转储到控制台以查看它们是什么。

window.addEventListener('message', (event) => console.log(event), false);

在我的 iframe 中,我将 postMessage() 移到了页脚,并检查了 div 是否只有在我提交表单后才可用。如果 div 存在,我会向 parent window 发送消息。这是我的 iframe 中的确切代码。

// if the form has submitted and the confirmation message
// div exists send a messge to the parent window
if (jQuery('#gform_confirmation_wrapper_1').length) {   

    // Send a message to the parent window  
    parent.postMessage({
        event: 'formSubmit'
    }, '*');

}

在我的 parent window 上,我创建了函数,检查了消息来自的域,并检查了使用 if (event.data.event === 'formSubmit') 发送的确切消息。如果该消息仅在存在表单确认 div 时从我的 iframe 发送,并且与 formSubmitted 完全匹配,那么我将事件推送到 Google 标签管理器的数据层。这是现在在我的开发站点上运行的确切代码。

// create function to push event to GTM if the iframe form has been submitted
function awReceiveMessage(event) {

    // set variable to url that the message is coming from 
    var origin = event.origin;

    // check if the message is coming from Polk 
    if (origin !== 'https://iframe.domain') {

        //stop function if it is not coming from Polk
        return;

    } else {

        // instantiating the GTM datalayer variable
        var dataLayer = window.dataLayer || (window.dataLayer = []);

        // if the message is formSubmit push the formSubmit event to the GTM datalayer
        if (event.data.event === 'formSubmit') {

            dataLayer.push({
                'event': 'formSubmit'
            });

        }

    }
}

// run awReceiveMessage() if a message is sent from the iframe to the parent
window.addEventListener('message', awReceiveMessage, false);

当在 iframe 中提交表单时,以上代码可以正常工作并在 parent 页面上正确触发 GTM 标记。