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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With