I just get started building my first Chrome extension. One functionality in my app is to get the name of the current site. For example, if the current url matches "*://*.facebook.com/", I would interpret this url and know the site name as Facebook.
How should I go about doing this?
It's not clear wheter you want to get the host name or the title of the page, but you can get both of them if you want.
Inside a content script you can do:
var site = location.hostname,
title = document.title;
alert("Site: " + site + " - Title: " + title);
If you want to do this from the background page and you don't want to use content scripts nor inject code in the tab then you can only get the host name:
var site;
chrome.tabs.query({/* some query */}, function(tabs) {
site = tabs[0].url.split("/")[2];
alert("Site: " + site);
});
If you also want to get the page title from the background page you'll need to use executeScript()
. NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript()
instead of chrome.tabs.executeScript()
.
var title;
chrome.runtime.onMessage.addListener(function(message, sender, sensResponse) {
if (message.title) {
title = message.title;
alert("Title: " + title);
}
});
chrome.tabs.query({/* some query */}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {code: "chrome.runtime.sendMessage({title: document.title});"});
});
For more informations about the methods I used in the above snippets you can see these documentation links:
chrome.tabs
API
chrome.tabs.query
methodchrome.tabs.executeScript
method (deprecated, manifest v2)chrome.scripting.executeScript
method (manifes v3)chrome.runtime.onMessage
eventchrome.runtime.sendMessage
methodIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With