4

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?

6
  • Are you trying to do so in a content script ? Jan 11, 2015 at 8:14
  • Any way will do, although I think it's impossible to do it in a content script (since we don't have access to chrome.tabs there). What I'm thinking of doing is to send a message to the background and get back the solution. Jan 11, 2015 at 8:18
  • 1
    I think it should work if you try to access window.location.host from the content script, since the script is injected to that page Jan 11, 2015 at 8:21
  • Yup it works. Great yet simple solution. Thank you! Jan 11, 2015 at 8:29
  • @OmriAharon Please make that into an answer. Avoid answering in comments - it cannot be marked as accepted, makes a bad question "track record" for the OP, and it's not obvious that the question is answered.
    – Xan
    Jan 11, 2015 at 9:12

2 Answers 2

7

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:

0
3

Since the content script is injected into the page, you could use window.location.host in the content script itself and get the name of your site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.