检测浏览器对窗口间通信的支持

时间:2013-02-25 06:12:04

标签: javascript browser-feature-detection

我有一些javascript依赖于使用window.open和窗口间通信(其中新的'子'窗口communicates success / failure to the 'parent' window)。

这种(窗口间通信)在大多数情况下工作正常,但对于某些不支持窗口间通信的浏览器不起作用。示例包括Windows PhoneiPhone's UIWebView

我目前做客户端(基于javascript)user-agent sniffing来检测这些情况 - 并回退到不同的代码路径来解决问题。

我可以使用用户代理嗅探的替代方法吗?

要清楚,window.open可以工作(其中的工作意味着'它打开请求的网址')。 不是可靠的是使用window.opener和postMessage进行从'child'到'parent'的窗口间通信。

1 个答案:

答案 0 :(得分:2)

在您的开启窗口消息回调中,您可以将回复发送回子窗口,如下所示:

function yourMessageCallback(event) {
  // your other handler stuff here...
  event.source.postMessage('Yeah I got it', event.origin);
}

然后你可以在发送方做一个计时器,你可以在答复到达时清除:

// do your postmessage here

function notReceived() {
  // do stuff if the message didn't go through
}

var messageTimer = setTimeout(notReceived, 500); // 500ms should be enough for everyone?

window.addEventListener('message', function(event) {
  // do necessary origin checks first etc... (not shown here)

  if (event.data == 'Yeah I got it') {
    clearTimeout(messageTimer);
    // do stuff if the message went through
  }
}, false);

我知道这可能是一个有点hackish的解决方案,但可能不如用户代理嗅探?

相关问题