简体   繁体   中英

Close Child Page on refreshing/closing Parent Page

I have a Parent Page which has a button to open a new url

function clickME(url) { 
    window.open(url,"URLname")
  }
<Button type="primary" size="sm" id="b" onClick={() => clickME(url) }>
    MyButton
</Button>

I want to close this 'URLname' when I close/reload the parent window. How can I do this?

I read about windows.close but haven't able to execute it. Can anyone help me with this please?

You can try following solution:

export default function App() {
  const [urlToClose, setUrlToClose] = React.useState(null);
  function clickME(url) {
    setUrlToClose(window.open(url, 'URLname'));
  }
  function closeTab() {
    if (urlToClose !== null) {
      urlToClose.close();
    }
  }
  return (
    <div>
      <button onClick={() => clickME('http://google.com')}>MyButton</button>
      <button onClick={() => closeTab()}>Close Tab</button>
    </div>
  );
}

If you want to close tab on same button, you can use conditional rendering for button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM