How do I prevent Google Chrome from blocking my popup?

前端 未结 7 1089
小鲜肉
小鲜肉 2020-11-30 01:21

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

相关标签:
7条回答
  • 2020-11-30 01:54

    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();
            });
    });
    
    
    0 讨论(0)
提交回复
热议问题