如何创建与父窗口具有相同状态的新窗口?

时间:2016-01-02 04:17:56

标签: javascript

我可以在javascript中以与父标签相同的状态打开新标签吗?如果是,我该怎么办?

我使用了window.open(),但它只是打开一个新的空白状态选项卡。

1 个答案:

答案 0 :(得分:2)

您无法准确创建具有相同状态的窗口。您解释它的方式,听起来像是fork父窗口,就像unix进程一样。

在您的情况下可能有用的是在窗口上使用postMessage方法在窗口之间发送消息对象。

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

来自mdn的样本:

/*
 * In window A's scripts, with A being on <http://example.com:8080>:
 */

var popup = window.open(...popup details...);

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
popup.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "http://example.org");

function receiveMessage(event)
{
  // Do we trust the sender of this message?  (might be
  // different from what we originally opened, for example).
  if (event.origin !== "http://example.org")
    return;

  // event.source is popup
  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);

这是一个非常简单的模式,但从那里,您应该能够发送更复杂的消息。