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

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'
});
});

Related

Chrome extension content script not being injected sometimes

I have a chrome extension for fillling forms on certain websites. This all works well, however sporadically the content script for filling the form doesn't get injected anymore, then I have to reinstall the extension to remediate the problem. This is the code I use for injecting the content script:
chrome.tabs.create({ url: url, active: true }, function (tab) { //create tab
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (info.status === 'complete' && tabId === tab.id) {
chrome.tabs.onUpdated.removeListener(listener);
chrome.tabs.executeScript(tab.id, { file: 'library.js', allFrames: true, runAt: "document_end" }, function () {
chrome.tabs.executeScript(tab.id, { file: 'fillForm.js', allFrames: true, runAt: "document_end" }, function () {
//inject content script
chrome.tabs.sendMessage(tab.id, { formData }); //send message to content script
});
});
}
});
});
I suppose it's some kind of a timing issue or something that changed in the Chrome api? Because the problem only occured recently.

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=") });
})
}
});

How to detect when the Chrome browser window is closed using JavaScript?

I am trying to detect the following scenarios:
User navigates away from the web page
User closes the tab
User opens a new tab (i.e. visibility is lost on the old tab)
User closes the browser
I am able to detect all four scenarios above in Safari, Firefox and Chrome, except for "User closes the browser" in Chrome (91.0.4472.114). Currently it does not emit an event which I am able to listen for.
This is my code:
window.onbeforeunload = function() {
// do something
}
window.addEventListener('pagehide', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('unload', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('beforeunload', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
// do something
}
}, { capture: true} );
As far as I can tell, I'm checking everything, but maybe I'm missing something?
Thanks for your help.

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

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

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.
}
}
});
});

Categories

Resources