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

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

问题描述

我有一个页面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?

推荐答案

您可以返回自定义诺言,并在需要时将其解析为以下代码

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天全站免登陆