Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: get current site name

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?

like image 446
hsiaomijiou Avatar asked Dec 26 '22 00:12

hsiaomijiou


1 Answers

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 method
    • chrome.tabs.executeScript method (deprecated, manifest v2)
  • chrome.scripting.executeScript method (manifes v3)
  • Message passing
    • chrome.runtime.onMessage event
    • chrome.runtime.sendMessage method
like image 53
Marco Bonelli Avatar answered Dec 28 '22 07:12

Marco Bonelli