有一个名为porthole的库,它基本上可以完成 SF. 的回答所描述的内容,但形式更正式。我刚刚写了一个网页来切换显示两个 iframe 之一。在我的顶级网页中
var windowProxy;
windowProxy = new Porthole.WindowProxy(baseURL + '/porthole/proxy.html', frameId);
windowProxy.addEventListener(onMessage);
...
function onMessage(messageEvent) {
if (messageEvent.origin !== baseURL) {
$log.error(logPrefix + ': onMessage: invalid origin');
console.dir(messageEvent);
return;
}
if (messageEvent.data.pong) {
pongReceived();
return;
}
$log.log(logPrefix + ': onMessage: unknown message');
console.dir(messageEvent);
}
...
var sendPing = function () {
$log.log(logPrefix + ': ping to ' + baseURL);
...
windowProxy.post({ 'ping': true });
};
加上一些额外的控制逻辑。在子网页中,以下是我必须添加的所有内容(加上portholeService.init()
来自控制器的调用):
// This service takes care of porthole (https://github.com/ternarylabs/porthole)
// communication if this is invoked from a parent frame having this web page
// as a child iframe. Usage of porthole is completely optional, and should
// have no impact on anything outside this service. The purpose of this
// service is to enable some failover service to be build on top of this
// using two iframes to switch between.
services.factory('portholeService', ['$rootScope', '$log', '$location', function ($rootScope, $log, $location) {
$log.log('Hello from portholeService');
function betterOffWithFailover() {
...
}
function onMessage(messageEvent) {
$rootScope.$apply(function () {
if (messageEvent.origin !== baseUrl) {
$log.error('onMessage: invalid origin');
console.dir(messageEvent);
return;
}
if (!messageEvent.data.ping) {
$log.error('unknown message');
console.dir(messageEvent.data);
return;
}
if (betterOffWithFailover()) {
$log.log('not sending pong');
return;
}
windowProxy.post({ 'pong': true });
});
}
var windowProxy;
var baseUrl;
function init() {
baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port();
windowProxy = new Porthole.WindowProxy(baseUrl + '/porthole/proxy.html');
windowProxy.addEventListener(onMessage);
}
return {
init: init
};
}]);
作为参考,这些页面使用AngularJS,以防$rootScope.$apply
您不熟悉等。