从新的子窗口中调用函数而不是父窗口

问题描述

我正在使用 react-new-window 在新窗口中加载一个小组件。在那里,它使用 html2canvas 导出为 png。我希望从新打开的窗口调用导出函数,以便可以导出其元素,而不是父窗口中的元素。

问题:总是从父窗口调用导出函数takeScreenShot()html2canvas在新的子窗口中找不到元素,因为它正在查询父窗口。

/*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>
      )}

我尝试从以下位置调用 takeScreenShot()

  1. 子窗口中按钮的 onClick 属性
  2. onopen 中的 <NewWindow/> 道具
  3. 来自以 [useEffect]NewWindow 作为参数的 showWindowPortal 钩子(这不应该起作用,我知道)

到目前为止没有任何效果函数内的 document.querySelector 始终在父函数内。

有什么想法吗?谢谢!

解决方法

我找到了解决方案。我需要引用新的子窗口,并在 html2canvas 中访问该引用的文档。

我添加了 name="exportPopup" 作为 <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);
      });
    });
  };

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...