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

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?

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

Is it possible to get HTTP status of created tab by browser.tabs.create({ url: 'https://exampleforerror.com/', active: false })?

there question is how to get http status code of newly created tab without fetch/XMLHttpRequest?
I tried with
browser.tabs.onUpdated.addListener(function (tabID, changeInfo, tab) {
console.log(changeInfo)
if (tabID === tabId && tab.status === 'complete') console.log(tab)
})
but it doesn't return any error status

Why sendMessage from the background script in a Chrome extension doesn't reach the needed tab?

In my Chrome extension I want:
Send a certain "pageURL" from the active tab to the content script.
Send "pageURL" from the content script to the background script.
From the background script browse all tabs in the window, choose one of them (different from the tab, from which "pageURL" has been sent) and send "pageURL" to the content script in this different tab.
In the chosen tab open the received "pageURL" from the content script.
The fragments of the source code I used:
main.js:
window.postMessage({"pageURL": "https://www.mytarget.com"}, window.origin);
It worked.
content_script.js:
addEventListener("message", (event) => {
console.log(`Event data is received in content_script.js`);
chrome.runtime.sendMessage(
{"request": "getTabs", "pageURL": event.data.pageURL}
}
});
chrome.runtime.onMessage.addListener( (message, sendResponse) => {
console.log(`Message is received in runtime listener for content_script.js`);
/* Something useful */
}
It worked.
background.js:
chrome.runtime.onMessage.addListener( (message) => {
if (message.request == "getTabs") {
chrome.tabs.query(
{ currentWindow: true }
).then(tabs => {
let targetTab = (() => {/* Something to find target tab */})();
if (targetTab) {
console.log(`Page URL in background.js is about to return`);
chrome.tabs.sendMessage(targetTab.id, { "pageURL": message.pageURL });
}
});
}
});
It worked too, but no message had been registered by either listener in the content script.
What is wrong with my approach?

Updating tab url while still conserving history chrome extension

I am making a chrome extension that redirects you from a youtube short to the actual video, and when you get redirected you can't go back to your previous page. Can anyone help? Here is my background.js code:
let enabled = true
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.url.startsWith("https://www.youtube.com/shorts") && enabled) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0]
chrome.tabs.update(activeTab.id, { url: activeTab.url.replace("shorts/", "watch?v=") });
})
}
});

chrome extension - issue with propertie "active" of chrome.tabs.create

I am creating a new tab and and injecting some code in it straight after.
But the problem is that the code to be injected is not injected properly when using the property active:true(which I need to use) on tabs.create.
Here is the code in popup.js:
chrome.tabs.create({url: "http://localhost:3000/", index: newTabId, active: false}, (newTab) => {
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// check status so that it sends only one message, and not one for each status change
if(changeInfo.status === "loading") {
if (tab.id === newTab.id) {
chrome.tabs.sendMessage(newTab.id, {message: "watch_video", videoData: selectedVideoData},
function (resp) {
console.log("Resp",resp);
return true;
}
);
}
}
});
})
Here is the problematic line: chrome.tabs.create({url: "http://localhost:3000/", index: newTabId, active: false}. When active is false, the code is injected, but when it is true, nothing seems to happen.
inject.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "watch_video") {
console.log("inject soon")
injectScript(request.videoData);
sendResponse("watch_video script is to be injected in " + window.location.href)
}
});
function injectScript(videoData) {
console.log("injected")
$(document).ready(function() {
document.test = "ABCDE"
const checkState = setInterval(() => {
$(".bkg").css({ "background-color": "#ffffff"})
}, 100)
})
}
Here I tried something with setInterval(), it does not work when active is true.
However it does work with a timeout. But does not not work without any timeout or interval when active is set to true.
I could use just use a timeout, but it is not really clean, I would prefer to understand why it behaves like it does. I am using react btw.
Here is what it is said about the active property:
Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see windows.update). Defaults to true.
Source: https://developer.chrome.com/extensions/tabs#method-create

Open tab, wait for it to finish loading then close it

I have written my first chrome extension today. What I want it to do is open a tab in the background (pinned), and after the page in the tab finishes loading, I want the tab to close.
So far I have:
chrome.tabs.create({url: target, selected: false, pinned: true});
What the above code does is open the tab in the background, and pin it.
How do I close the tab once it has finished loading?
chrome.tabs.create({url: target, selected: false, pinned: true}, myTab => {
function listener(tabId, changeInfo, tab) {
// make sure the status is 'complete' and it's the right tab
if (tabId === myTab.id && changeInfo.status == 'complete') {
chrome.tabs.remove(myTab.id);
chrome.tabs.onUpdated.removeListener(listener);
}
};
chrome.tabs.onUpdated.addListener(listener);
});
You can either bind a chrome.tabs.onUpdated or a chrome.webNavigation.onCompleted event to detect that a page has finished loading, or insert a content script to close the tab.
Using the webNavigation.onCompleted event
var tabsToClose = {};
chrome.webNavigation.onCompleted.addListener(function(details) {
if (details.frameId !== 0) return; // Only process top-frame requests
var tabId = details.tabId;
if (tabsToClose[tabId]) {
delete tabsToClose[tabId];
chrome.tabs.remove(tabId);
}
});
chrome.tabs.create({url: target, selected: false, pinned: true}, function(tab) {
tabsToClose[tab.id] = 1;
});
Note: I assumed that navigation will always succeed. You should also bind a webNavigation.onErrorOccurred event to close the tab on failure.
Using a content script
By using runAt: 'document_idle' (default), window.close(); will be inserted once the page has finished loading.
chrome.tabs.create({url: target, selected: false, pinned: true}, function(tab) {
chrome.tabs.executeScript(tab.id, {
code: 'window.close();',
runAt: 'document_idle'
});
});

Categories

Resources