How to get access of document object of a window o

2019-01-29 11:34发布

问题:

I open a website in a new tab through javascript by writing the following code in the browser console:

var win = window.open("http://staging.redefinewebs.in/wildgoose-const/wp-admin/post-new.php", "mywin", '');

Now I want to add text in a field in the newly opened tab. But for that I need the access to win.document. When I write win.document in the console I get the following error:

Error: Permission denied to access property "document"

This error doesn't appear if I open other websites in new tab. So,

How to get access of document object of a window opened in a new tab with window.open?

回答1:

How to get access of document object of a window opened in a new tab with window.open?

If the window is opening a document from a different origin, you don't; cross-origin access is denied by the browser because of the Same Origin Policy. From the error in your question, that would seem to be the case here.

If the window contains a document from the same origin, you can access it as you've shown; but note that it may still be loading immediately after you call window.open and you might need to wait for it to finish doing so, perhaps with the DOMContentLoaded event.



回答2:

You cannot access a child window's DOM, if it violates the Same Origin Policy.

You can access the DOM of a child window, only if the following three conditions are satisfied.

  • Both windows have same protocol (http/https)
  • Both windows have same host (google.com and news.google.com are different)
  • Both windows have same port (google.com:80 and google.com:443 are different)