Chrome extension: get the current site name
2 answers
It's not clear if you want to get the hostname or the page title, but you can get both if you want.
Inside the content script, you can:
var site = location.hostname,
title = document.title;
alert("Site: " + site + " - Title: " + title);
If you want to do it from the man page and you don't want to use content scripts and don't enter code in the tab, you can only get the hostname:
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 need to implement some messages:
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 information on the methods I used in the snippets above, you can see these documentation links:
+2
source to share