I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?
Use chrome.tabs.query.
ManifestV3:
(async () => {
// see the note below on how to choose currentWindow or lastFocusedWindow
const [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
console.log(tab.url);
// ..........
})();
ManifestV2/V3:
// see the note below on how to choose currentWindow or lastFocusedWindow
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
// use `url` here inside the callback because it's asynchronous!
});
You'll need to request tabs
or activeTab
permission in your extension manifest:
"permissions": [ ...
"tabs"
]
or
"permissions": [ ...
"activeTab"
]
Prefer activeTab
if your code uses chrome.tabs.query after the user explicitly invoked the extension (clicked its icon or its context menu item or pressed its chrome.commands
hotkey) because this permission doesn't add any warnings when installing the extension, unlike tabs
that adds Read your browsing history
which may scare some users.
"Current tab" definitions depends on your needs:
currentWindow: true
always uses the window where your popup was initially shown regardless of whether the user has switched to another window after opening the popup. There's usually no difference at the start of the popup script, because it runs while the original window is still focused. The termcurrentWindow
means "currently running extension code's window".lastFocusedWindow: true
uses the actually focused window at the time of the call (typically the topmost window), which may differ from the original window showing the popup in case the user has switched to another window (or your extension opened a new window) and chrome.tabs.query is called after that e.g. in a click listener for a button in the popup.A
chrome.runtime.onMessage
listener should normally usesender.tab
from the sender parameter.
async/await
I guess. –
Anamorphic Other answers assume you want to know it from a popup or background script.
In case you want to know the current URL from a content script, the standard JS way applies:
window.location.toString()
You can use properties of window.location
to access individual parts of the URL, such as host, protocol or path.
window.location.host
to see if Im at "stackoverflow.com" or not. –
Tummy match:"<all_urls>"
situation on content_script section and Chrome is not reccomend <all_urls>. –
Bone contentScript.js
and not in the background.js
. Just pass any data you've filtered from the URL into the message to background.js
. Example: let message = { type: "fetchVideoDate", id: getVideoId() };
where getVideoId()
contains an execution of window.location.toString()
. Otherwise you'll get some chrome://temp_background_file.html
data. Also note that sometimes message
is called request
. –
Jamesy Warning! chrome.tabs.getSelected
is deprecated. Please use chrome.tabs.query
as shown in the other answers.
First, you've to set the permissions for the API in manifest.json:
"permissions": [
"tabs"
]
And to store the URL :
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
});
chrome.tabs.getSelected
is undefined, hould I ask it in a separate question? –
Devastating chrome.tabs.getSelected
method has been deprecated, the correct method is listed at this below answer. –
Danaedanaher main.js
, any guidance? –
Percuss The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:
var tablink;
chrome.tabs.getSelected(null,function(tab) {
tablink = tab.url;
});
console.log(tablink);
The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.
Try something like:
chrome.tabs.getSelected(null, function(tab) {
myFunction(tab.url);
});
function myFunction(tablink) {
// do stuff here
console.log(tablink);
}
This is a pretty simple way
window.location.toString();
You probaly have to do this is the content script because it has all the functions that a js file on a wepage can have and more.
Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)
Additionally it is a nice working code example, which i prefer motstly over reading Documents.
Can be found here: Email this page
This Solution is already TESTED.
set permissions for API in manifest.json
"permissions": [ ...
"tabs",
"activeTab",
"<all_urls>"
]
On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated
chrome.tabs.onActivated.addListener((activeInfo) => {
sendCurrentUrl()
})
On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged
chrome.tabs.onSelectionChanged.addListener(() => {
sendCurrentUrl()
})
the function to get the URL
function sendCurrentUrl() {
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url
console.log(tablink)
})
async function getCurrentTabUrl () {
const tabs = await chrome.tabs.query({ active: true })
return tabs[0].url
}
You'll need to add "permissions": ["tabs"]
in your manifest.
For those using the context menu api
, the docs are not immediately clear on how to obtain tab information.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log(info);
return console.log(tab);
});
You have to check on this.
HTML
<button id="saveActionId"> Save </button>
manifest.json
"permissions": [
"activeTab",
"tabs"
]
JavaScript
The below code will save all the urls of active window into JSON object as part of button click.
var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
myArray = [];
chrome.tabs.query({"currentWindow": true}, //{"windowId": targetWindow.id, "index": tabPosition});
function (array_of_Tabs) { //Tab tab
arrayLength = array_of_Tabs.length;
//alert(arrayLength);
for (var i = 0; i < arrayLength; i++) {
myArray.push(array_of_Tabs[i].url);
}
obj = JSON.parse(JSON.stringify(myArray));
});
}, false);
If you want the full extension that store the URLs that opened or seen by the use via chrome extension:
use this option in your background:
openOptionsPage = function (hash) {
chrome.tabs.query({ url: options_url }, function (tabs) {
if (tabs.length > 0) {
chrome.tabs.update(
tabs[0].id,
{ active: true, highlighted: true, currentWindow: true },
function (current_tab) {
chrome.windows.update(current_tab.windowId, { focused: true });
}
);
} else {
window.addEventListener(hash, function () {
//url hash # has changed
console.log(" //url hash # has changed 3");
});
chrome.tabs.create({
url: hash !== undefined ? options_url + "#" + hash : options_url,
});
}
});
};
you need index.html file also. which you can find in the this Github the manifest file should be like this:
{
"manifest_version": 2,
"name": "ind count the Open Tabs in browser ",
"version": "0.3.2",
"description": "Show open tabs",
"homepage_url": "https://github.com/sylouuu/chrome-open-tabs",
"browser_action": {},
"content_security_policy": "script-src 'self' https://ajax.googleapis.com https://www.google-analytics.com; object-src 'self'",
"options_page": "options.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"web_accessible_resources": ["img/*.png"],
"permissions": ["tabs", "storage"]
}
The full version of simple app can be found here on this Github:
https://github.com/Farbod29/extract-and-find-the-new-tab-from-the-browser-with-chrome-extention
© 2022 - 2024 — McMap. All rights reserved.