【问题标题】:The target origin does not match the recipients window's origin目标来源与收件人窗口的来源不匹配
【发布时间】:2020-11-25 11:54:31
【问题描述】:

我正在尝试从我在 Angular 网站的 iframe 中托管的 MVC 网站发布消息,但是在使用 window.postMessage 时出现上述错误。这是我的代码:

在 MVC 站点中(通过 iframe 调用):

// I need to tell Angular when something has changed here to update their menu
var data = { foo: 'bar' }
window.postMessage(data, 'http://localhost:4200/');

Angluar 收听留言:

renderer.listen('window', 'message', (event) => {
if (event.origin.startsWith('http://localhost')) {
     console.log(event.data) // should output: {foo: 'bar'}
   }
}); 

我在这里错过了什么?

【问题讨论】:

    标签: javascript angular typescript iframe


    【解决方案1】:

    使用此代码,您尝试将消息从 iframe 发布到 iframe 本身。发生有关目标来源的错误是因为接收窗口的来源实际上是嵌入式应用程序的来源。实际上,如果您想通知父窗口,请不要将其称为window,而是将其称为window.parentwindow 是 MVC 应用程序的window):

    window.parent.postMessage(data, 'http://localhost:4200/');
    

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2018-12-02
      • 1970-01-01
      • 2018-01-15
      • 2019-12-30
      • 2019-05-25
      • 2021-05-26
      • 1970-01-01
      • 2022-06-22
      相关资源
      最近更新 更多