How to detect no internet connection on new tab in Chrome Extension

Viewed 849

I open a new tab with the following code:

chrome.tabs.create({url: "http://website.com", active: true}, async tab => {
    chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (info.status === 'complete' && tabId === tab.id) {
            // here my tab is loaded, but I don't know if it is
            // the requested website or the Chrome page that says "There is no Internet connection"
            // How can I find out?
        }
    });
});

How do I know if my tab loaded the requested page or is displaying the "There is no Internet connection" or Error 404 page?

1 Answers

You can check if navigator.onLine is true. If so, you are online and the page you requested has been correctly loaded, otherwise you are not, and the page which is being displayed is the "no internet connection" page.

As simple as this:

chrome.tabs.create({url: "http://website.com", active: true}, async tab => {
    chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (info.status === 'complete' && tabId === tab.id) {
            if (navigator.onLine) {
                // Page correctly loaded.
            } else {
                // No internet connection.
            }
        }
    });
});
Related