Javascript 如何在Chrome Extension的新选项卡上检测到没有internet连接
我使用以下代码打开一个新选项卡:Javascript 如何在Chrome Extension的新选项卡上检测到没有internet连接,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我使用以下代码打开一个新选项卡: 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) {
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?
}
});
});
如何知道我的选项卡是否加载了请求的页面,或显示了“没有Internet连接”或错误404页面?您可以检查
navigator.onLine
是否为true
。如果是,则表示您处于联机状态,并且您请求的页面已正确加载,否则表示您未联机,并且显示的页面为“无internet连接”页面
就这么简单:
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.
}
}
});
});
您可以检查
navigator.onLine
是否为true
。如果是,则表示您处于联机状态,并且您请求的页面已正确加载,否则表示您未联机,并且显示的页面为“无internet连接”页面
就这么简单:
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.
}
}
});
});
非常感谢您提供的提示,但对我不起作用,因为此方法无法检测404错误。@Worker您在问题中没有提到任何关于404错误的内容。。。您说“我不知道是否是我们的目标URL或Chrome页面显示连接不可用”。非常感谢您的提示,但对我无效,因为此方法不会检测404错误。@Worker您在问题中没有提到任何关于404错误的内容。。。你说“我不知道是不是我们的目标URL或Chrome页面显示连接不可用”。