Search code examples
google-chrome-extension

Open the same window opened from the popup.html when a button is clicked


I have a chrome extension and a popup.html, This popup.html UI has a single button when clicked it would open a web page in the external popup window

popup.html

<body>
    <article style="width: 34rem">
        <button id="open">Click to open the App</button>
    </article>
<script src="popup.js"></script>
<body>

The popup.js code

$(document).ready(function() {
    $("#open").click(function() {
        window.open("https://www.example.com",'The title','height=678,width=650').focus();
    });
});

The user clicks the button on popup.html and it opens a window and the new window gets focused (I have no problem with that), The new window can be minimized by the user when its not active.

Say a user minimized the new window and again clicks the button on the popup.html another instance of the new window is created.

I am looking for a way to open focus the same earlier minimized window instead of new. How do I achieve it?


Solution

  • Hope this will solve your problem

    $(document).ready(function() {
        $("#open").click(function() {
            chrome.tabs.query({
                title: 'Your title name'
            }, tabs => {
                if (!tabs.length) {
                    window.open("https://www.example.com", 'Your title name', 'height=678,width=650').focus();
                    return;
                }
                chrome.windows.update(tabs[0].windowId, {
                    focused: true
                });
                chrome.tabs.update(tabs[0].id, {
                    active: true
                });
            });
        });
    });