On my website there is a button that just used to call a function that calls window.open
, however, recently an adjustment was needed to do a server-side check b
Here is a vanilla JavaScript solution, I am using for one of my websites, to bypass the popup blocker in Chrome.
Let us say we have the following HTML button:
<button id="clickMe">Click Me!</button>
Now when the user clicks on the button, the first thing you should do is open an empty new window. After the Fetch request is finished, update the actual window URL. If the request fails, simply close the window:
const button = document.querySelector('#clickMe');
// add click event listener
button.addEventListener('click', () => {
// open an empty window
const tab = window.open('about:blank');
// make an API call
fetch('https://reqres.in/api/users')
.then(res => res.json())
.then(json => {
// TODO: do something with JSON response
// update the actual URL
tab.location = 'https://attacomsian.com';
tab.focus();
})
.catch(err => {
// close the empty window
tab.close();
});
});