How can I close window in a React Component? - reactjs

This sounds ridiculously simple but I am not be able to find any solution for this from Google.
On my page, I have a button to close the page itself
<Button onClick={() => window.close()} >Close</Button>
But everytime triggering the button, i got the warning
Scripts may close only the windows that were opened by it.
I am using react-native for my mobile app, it connects to keycloak to (through WebView of RN) open Facebook authentication page and then, after that, keycloak redirects to success page (localhost/login/success which has the button to close the page itself. The page is under next.js). Even i access localhost/login/success directly on browser, I cannot close page neither
Update I managed to work around by using onNavigationStateChange and check if the navState.url contains the success/login or not to trigger the state and close the WebView. But i am still curious about how to close the window in React ?

You can use onMessage prop to communicate between WebView and React-Native.
A function that is invoked when the webview calls
window.postMessage. Setting this property will inject a
postMessage global into your webview, but will still call
pre-existing values of postMessage.
Example
_onMessage = (message) => {
console.log(message);
}
render() {
return (<WebView ref={(ref) => { this.webView = ref; }} onMessage={this._onMessage} ..otherProps />);
}
// In your webview inject this code
<script>
window.postMessage("Sending data from WebView");
</script>

Related

popstate - need to click twice on back button to actually get back on react-native

working on single page appliction trying use popstate to navigate back to previous page but I have to click twice to take me back. I want to make it happen for one click. console showing for each click but needs twice click to navigate back. using react native.
also using props.navigator.push for single page application
useEffect(() => {
window.addEventListener('popstate', (event) => { console.log( event) });
}, []);

React Router scroll page to top when routed to new page

I am trying to implement a way where whenever I change a page, it scrolls to the top. So far, I have tried adding this:
useEffect(() => {
window.scrollTo(0, 0);
}, []);
But this does not help. Is there anyway to make it so whenever a new link is opened through react-router, the app automatically goes to the top? I am using component based functions and would prefer a solution that uses hooks.

How to prevent "Add to home screen" from appearing on certain urls of same webapp?

I have a webapp that shows some content on say,
test.com and special.test.com
I have setup PWA using React Typescript + PWA template.
The "Add to Home Screen" appears on both the urls.
Is their a way to prevent the install option from appearing in special.test.com
self.addEventListener('beforeinstallprompt', (event) => {
const subdomainName = self.location.host.split('.')[0];
console.log('PWA_INSTALL_CALL', subdomainName);
if (subdomainName === 'special') {
event.preventDefault();
}
});
I have added this event listener to service-worker.ts but this function doesn't seem to be called since I'm not seeing console.log statement on Chrome dev console.
Really stuck here!
Please help. Thanks!
You need to listen for beforeinstallprompt in the application context, not in a service worker context.

How to prevent user from going back in react-router-dom?

I'm using react-router-dom for routing in my reactjs app. And i want to prevent user from going back after login i.e i don't want to user go back again on login screen when he hit back button on browser after login.
Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.
componentDidUpdate() {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener('popstate', function(event) {
window.history.pushState(null, document.title, window.location.href);
});
}
This will prevent to user go back and uses the current page as a refernce for history object . so incase of user even click on back button of browser, they can not go backword in the last page.
You can checkout this codesandbox example may be that will help you or someone who is looking for the same.In this we can prevent the user to go back to previous page,For more detail checkout this medium article. here is small part of the code
componentDidMount() {
const { history } = this.props;
window.addEventListener("popstate", () => {
history.go(1);
});
}
for full working example click on this link.
Are you using redux? other wise you can add something on your render that checks if the user is already logged in it redirects him back to the page he was like:
import { Redirect } from 'react-router'
render(){
//I store my user JWT on this.props.currentUser redux state
this.props.currentUser && <Redirect to={'whatever page you want'} />
//OR you can also, if you have history, history.goBack()
So instead of forbidding going back, you forbid the user to ever going to the login page while logged in, it redirects him somewhere or back to where he was
window.addEventListener('popstate', function(event) {
});
use this function this will read your browser back button click event and after that whatever condition you want you can apply

Is there any possible ways to update (synchronize) localStorage for all opened tabs (browser windows) in React JS (Redux)?

I faced with interesting problem in React JS. I'm opening main page of my application with the list of products. Then I chose few products and open them in separate tabs (browser windows). When I'm starting to work with each tab my localStorage changes (product is added to cart) but only on the current page which I'm working on. Is there any possible ways to update (synchronize) localStorage for all opened tabs (browser windows) in React JS (Redux), not only on current page?
You want to add an event listener using window.addEventListener('storage', function() {}) and update your application state either using setState or dispatching an action with redux
componentDidMount() {
window.addEventListener('storage', this.handleStorageChange);
}
componentWillUnmount() {
window.removeEventListener('storage', this.handleStorageChange)
}
handleStorageChange(storageEvt) {
// setState or dispatch a redux action
this.setState({
});
}

Resources