calling a function from a new, child, window in react instead of parent window

921 Views Asked by At

I am using react-new-window to load a small component in a new window. There it is staged to export as a png using html2canvas. I wish to call the export function from the newly opened window, so that its element can be exported, not an element from the parent window.

Problem: the export function takeScreenShot() is always called from the parent window and html2canvas cannot find the element in the new child window as it is querying the parent window instead.

/*Export is the parent, functional component, which creates a pop up menu so user can copy item to clipboard, or export to a file as a screenshot*/

const Export = (props) => {
/*redacted*/
const [showWindowPortal, toggleWindowPortal] = useState(false); /*toggles new window with specific item */
const takeScreenShot = () => {
    let id = `#${card.tag}`;
    html2canvas(document.querySelector(id), {}).then((canvas) => {
     /*redacted*/
      });
    });
  };
return(
/*redacted*/
      {showWindowPortal && (
        <NewWindow
          onUnload={() => {
            toggleWindowPortal(false); //turns off toggle on close
          }}

          onOpen={() => console.log('opened')} //this property's function is called in the parent
          features={features}
        >
          <div id={card.tag}>
            <Card/>
          </div>
        </NewWindow>
      )}

I have tried calling takeScreenShot() from:

  1. a button's onClick prop in the child window
  2. the onOpen prop in <NewWindow/>
  3. from a [useEffect] hook with NewWindow or showWindowPortal as a parameter (this shouldn't have worked, i know)

and so far nothing has worked and the document.querySelector inside the function always inside of the parent function.

Any thoughts? Thanks!

1

There are 1 best solutions below

0
On

I found a solution. I needed to reference the new child window, and access that reference's document in html2canvas.

I added name="exportPopup" as a prop to <NewWindow/>.

var newWindow = window.open('', 'exportPopup'); //Reference the popup
  const takeScreenShot = () => {
    let id = `#${card.tag}`;
    console.log(id);
    //use the reference for html2canvas
    html2canvas(newWindow.document.querySelector(id), {}).then((canvas) => {
      canvas.toBlob((blob) => {
        var file = new File([blob], 'test.png', {
          type: 'application/octet-stream',
        });
        document.location.href = URL.createObjectURL(file);
      });
    });
  };