跨页面异步通信 [英] Asynchronous communication cross pages

查看:27
本文介绍了跨页面异步通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面 addin.html.它可以通过

I have a page addin.html. It can popup another page editor (which is not necessarily in the same domain) by

popup = window.open("https://localhost:3000/#/posts/editor/", "popup")

然后,两个页面每个内部有一个监听器,可以通过

Then, the two pages have each one listener inside, and can send data to each other by

// listen:
function receiveMessage(event) {
    document.getElementById("display").innerHTML = JSON.stringify(event.data);
}
window.addEventListener("message", receiveMessage, false);

// send:
function sendMessage() {
    popup.postMessage("data", popup.location.href);
}

editorui-router 实现.最初,它在加载页面之前解析 init:

editor is realised by ui-router. Initially, it resolves init before loading the page:

.state('editor', {
    controller: 'EditorCtrl',
    resolve: { init: [ ... ] },
    ...
};

app.controller('EditorCtrl', ['$scope', 'init', function ($scope, init) {
    ...
}]

我现在想要实现的是,addin.html弹出editor时,它会向editor发送一些数据,并且init 需要在加载页面之前解析此数据. editor 可能会在从 addin.html 接收数据之前挂起.

What I want to implement now is, when addin.html popups editor, it sends some data to editor, and init needs to resolve this data, before loading the page. editor could hang before receiving the data from addin.html.

有谁知道如何修改接收者和发送者(以及其他东西)来实现这一点?

Does anyone know how to amend the receivers and senders (and something else) to accomplish this?

推荐答案

你可以返回一个自定义的 promise 并在任何时候解决它,如下代码

You could return a custom promise and resolve it whenever you want as the following code

.state('editor', {
  controller: 'EditorCtrl',
  resolve:{
    init: function($q){
         var deferred = $q.defer();
         window.addEventListener("message", function(event){
              deferred.resolve(event.data);
         }, false);
         return deferred.promise;
     }
  }
});

控制器在实例化之前等待上述项目完全解析.

The controller waits for above item to be completely resolved before instantiation.

这篇关于跨页面异步通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆