Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Getting a page title and meta description and using them as variables for a chrome extension

I have a script that gets the title from a tab and assigns it to a variable. However, I need to also get the meta desc and title properties for use in an input field.

I am not sure if I can achieve that with this:

chrome.tabs.getSelected(null, function(tab) {  
    var currentTitle = tab.title;  
});

Then I need to get the Meta description, which I don't believe I can get from the tab data.

This is the HTML I am getting the description from:

<meta name="description" content="contentstuffya" />

This is the Javascript I am using to get it outside of the extension:

document.getElementsByName('description')[0].getAttribute('content');

How would I best do this given the data that I have?

like image 480
jonode Avatar asked Oct 17 '13 13:10

jonode


1 Answers

The value of a <meta> tag can only be read through a content script. Here's an example:

var code = 'var meta = document.querySelector("meta[name=\'description\']");' + 
           'if (meta) meta = meta.getAttribute("content");' +
           '({' +
           '    title: document.title,' +
           '    description: meta || ""' +
           '});';
chrome.tabs.executeScript({
    code: code
}, function(results) {
    if (!results) {
        // An error occurred at executing the script. You've probably not got
        // the permission to execute a content script for the current tab
        return;
    }
    var result = results[0];
    // Now, do something with result.title and result.description
});

At the first line, I locate the <meta name="description"> element. At the second line, I read the value of its content attribute if the element is present.
The callback of chrome.tabs.executeScript receives the last expression's return value, so I've put an object literal (wrapped in parentheses) at the end of the code.

like image 191
Rob W Avatar answered Nov 05 '22 19:11

Rob W