this question asks way open new window using window.open , inject script. not possible because of cross-domain security issues.
however, problem want exact same thing, except same domain same domain. possible?
note .write not solve problem because wipes html page first.
you can this:
var thewindow = window.open('http://stackoverflow.com'), thedoc = thewindow.document, thescript = document.createelement('script'); function injectthis() { // code want inject goes here alert(document.body.innerhtml); } thescript.innerhtml = 'window.onload = ' + injectthis.tostring() + ';'; thedoc.body.appendchild(thescript); this seems work:
var thewindow = window.open('http://stackoverflow.com'), thescript = document.createelement('script'); function injectthis() { // code want inject goes here alert(document.body.innerhtml); } // self executing function thescript.innerhtml = '(' + injectthis.tostring() + '());'; thewindow.onload = function () { // append script new window's body. // seems work `this` this.document.body.appendchild(thescript); }; and if reason want use eval:
var thewindow = window.open('http://stackoverflow.com'), thescript; function injectthis() { // code want inject goes here alert(document.body.innerhtml); } // self executing function thescript = '(' + injectthis.tostring() + '());'; thewindow.onload = function () { this.eval(thescript); }; what (explanation first bit of code. examples quite similar):
- opens new window
- gets reference new window's
document - creates script element
- places code want 'inject' function
- changes script's
innerhtmlload said function when window loads,window.onloadevent (you can useaddeventlistener). usedtostring()convenience, don't have concatenate bunch of strings.tostringreturns wholeinjectthisfunction string. - appends script new window's
document.body, won't append document loaded, appends before loads (to empty body), , that's why have usewindow.onload, script can manipulate new document.
it's idea use window.addeventlistener('load', injectthis.tostring()); instead of window.onload, in case have script within new page uses window.onload event (it'd overwrite injection script).
note can inside of injectthis function: append divs, dom queries, add more scripts, etc...
also note can manipulate new window's dom inside of thewindow.onload event, using this.