user3056783
user3056783

Reputation: 2626

Reference to new window after calling `window.open()` returns null in IE11 and MS Edge

I am writing a React app, which is supposed to fetch data from server (binary pdf) and display it as PDF in new tab/window. I know how to figure out the displaying part, the problem is that the reference in my code to newly created window is lost. When you put the following file in vanilla create-react-app project and import it, you will see that the variable _window will return new window object on Chrome and Firefox but on Windows 7 (IE11) and Windows 10 (MS Edge) will return null.

import React, { Component } from 'react';

export default class Container extends Component {
  fetch() {
    const data = {
      user: 'User1',
      text: 'This is some text',
    }
    const user = document.createElement('h2');
    user.innerHTML = data.user;
    const text = document.createElement('p');
    text.innerHTML = data.text;
    const _window = window.open('about:blank', 'w1');
    console.log(_window);
    _window.document.body.appendChild(user);
    _window.document.body.appendChild(text);
  }

  render() {
    return (
      <div>
        <button onClick={this.fetch.bind(this)}>Fetch!</button>
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

This disallows me to modify DOM of newly created window object. (I know most React folks will probably say to put it in the component and display it there but I need this to be done in certain way).

I have already tried reading this and this and also turning off protected mode in IE but it does not work.

Upvotes: 1

Views: 3185

Answers (1)

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

It seems your problem isn't because of _window is null in IE/Edge, but you haven't created elements in the child window context which is required in IE/Edge.

So open your child window first and then create elements which you are going to append to the child window in the child window context as follows.

var _window = window.open('', 'w1');
var _contents = _window.document.createElement('div');

Find your updated codepen here.

Upvotes: 1

Related Questions