3

過去には、これは機能していました:

// writing
var newTab = window.open();
newTab.document.write("<html><head><title>I'm just a tab</title></head>");
newTab.document.write("<body id='hello'>With some text on it</body>");
newTab.document.write("</html>");
newTab.document.close();

// reading what was wrote
newTab.document.getElementById('hello').addEventListener("click", custom_search_function(), false);

ただし、このコードを実行しようとすると、Firefox でセキュリティ エラーが表示されます。

Error: SecurityError: The operation is insecure.

フォーラムで代替案を検索しましたが、これは機能します:

var textOnPage = "<html><head><title>I'm just a tab</title></head><body>";
var newTab = window.open("data:text/html;charset=UTF-8," + encodeURIComponent(textOnPage));
newTab.document.close();

しかし、私は経由でページにアクセスできませんgetElementById

newTab.document.getElementById('hello').addEventListener("click", custom_search_function(), false);

戻り値:

Error: TypeError: newTab.document.getElementById(...) is null

この新しいタブに書き込んでから、次のような関数を使用して戻って読み取るにはどうすればよいgetElementByIdですか?

4

2 に答える 2

2

You're falling foul of the Single Origin Policy. When you open a new window without a URL, by definition it can't have the same domain name as the original (opener) window.

You could instead have the window.open() call open another URL on your site (mostly blank html) and as part of its body.onload event handler (or jQuery.ready()) you could set up an event handler for the message event like this:

$(document).ready(function(){
   window.addEventListener("message", receiveMessage, false);
});

function receiveMessage(evt)
{
  if (evt.origin !== "https://your-domain.here")
    return;

  // do something with evt.data
  $(document.body).append(""+evt.data);
}

In your originating window you call:

otherWindow.postMessage(message, "https://your-domain.here");

The postMessage API is now well supported across a variety of modern browsers.

You'll still not be able to directly reach in to maniuplate the content of otherWindow, but you can post messages back from otherWindow to your originating window to achieve the same effect. (e.g: put your content manipulation code in otherWindow's content and 'call' it from your originating window).

于 2013-08-10T09:50:09.530 に答える