flaviu
flaviu

Reputation: 163

Run javascript code inside new window in Internet Explorer

I am trying to run some injected javascript code in a blank new popup

var popup = window.open('', 'name', options);
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.text = scriptSource;
popup.document.body.appendChild(scriptElement);

The javascript code works in FF and Chrome but I receive a HierarchyRequestError in IE (11). I've found an alternative way to write the last line with this one popup.document.head.innerHTML = scriptElement.outerHTML; but in this case the javascript is not recognised in any browser.

Upvotes: 0

Views: 340

Answers (1)

DracoBlue
DracoBlue

Reputation: 491

In PhpDebugToolbar at https://github.com/DracoBlue/PhpDebugToolbar/blob/master/pub/PhpDebugToolbar.js#L913 I use the following snippet, to create or update a custom PopUp with custom content.

var detail = window.open('', "php_debug_toolbar_window_" + key, "width=800,height=400,status=yes,scrollbars=yes,resizable=yes");
detail.document.write( [
    '<script type="text/javascript">',
    'if (!document.body) {document.write("<html><head><title></title></head><' + 'body></' + 'body></html>"); }',
    'document.getElementsByTagName("title")[0].innerHTML = ' + JSON.stringify(title) + ';',
    'var content = document.getElementById("content");', 'if (content) {', '    document.body.removeChild(content);', '}',
    'content = document.createElement("div");', 'content.id="content";', 'content.innerHTML = ' + JSON.stringify(html) + ';',
    'document.body.appendChild(content);', '<' + '/script>'
].join("\n"));

The important parts:

  • use document.write to initialize html>head+html>body structure
  • use a #content (or any other id) div for your content
  • JSON.stringify your content and set it with .innerHTML-Property of your #content div in JS

This is working for me quite good so far, so I am sure you can add your script tag like this, too.

Upvotes: 1

Related Questions