Chrome Extension: change title of tab - javascript

I've looked at other posts talking about using document.title to rename the title of a tab but I can't seem to get it to work.
I'm using a background script to send a message to the content script.
background.js
/* gets current tab */
chrome.tabs.query({ active: true, currentWindow: true }, function (tab)
{
var promptUser = prompt("Rename tab:");
chrome.tabs.sendMessage(tabs[0].id, {title: promptUser}, function(response) {});
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
/* custom title */
if (request.title)
{
document.title = request.title;
}
})

Related

How to pass Data between files Chrome Extension?

Currently, I mainly work with two files, background.js and popup.js.
In background.js
I have a bunch of functions that let me store data in an IndexedDB. And in popup.js I call the functions like this:
chrome.runtime.sendMessage({
message: "insert",
payload: [
{
url: form_data.get("message"),
text: form_data.get("message"),
},
],
});
Depending on the message, a certain function is called. When the function has successfully executed I do this from the background.js file:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "insert") {
let insert_request = insert_records(request.payload);
insert_request.then((res) => {
chrome.runtime.sendMessage({
message: "insert_success",
payload: res,
});
});
});
This is my problem:
How do I send data from background.js to popup.js. What I want is to get the URL of the current page, and then send it to popup.js and store it in the Database.
I have already looked at already existing posts, but none of them really helped.
Can someone please help me out.
Update
Currently I use this is in background.js to get the current URL. It works just fine. But how can I pass the tab.url to my popup.js file?:
let activeTabId, lastUrl, lastTitle;
function getTabInfo(tabId) {
chrome.tabs.get(tabId, function (tab) {
if (lastUrl != tab.url || lastTitle != tab.title)
console.log((lastUrl = tab.url), (lastTitle = tab.title));
});
}
chrome.tabs.onActivated.addListener(function (activeInfo) {
getTabInfo((activeTabId = activeInfo.tabId));
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (activeTabId == tabId) {
getTabInfo(tabId);
}
});

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?

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

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