Close Child Page on refreshing/closing Parent Page
Problem Description:
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?
Solution – 1
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.