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:
- a button's
onClickprop in the child window - the
onOpenprop in<NewWindow/> - from a
[useEffect]hook withNewWindoworshowWindowPortalas 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!
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/>.