Chrome extension: get the current site name

I just started building my first Chrome extension. One function in my application is to get the name of the current site. For example, if the current url matches "*: //*.facebook.com/", I would interpret that url and know the site name as Facebook.

How should I do it?

+3


source to share


2 answers


Since the script content is injected into the page, you can use window.location.host

in the script content itself and get the name of your site.



+2


source


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







All Articles