jon*_*ode 5 javascript google-chrome-extension
我有一个脚本从标签中获取标题并将其分配给变量.但是,我还需要获得meta desc和title属性在使用input领域.
我不确定我能否实现这一目标:
chrome.tabs.getSelected(null, function(tab) {
var currentTitle = tab.title;
});
Run Code Online (Sandbox Code Playgroud)
然后我需要获得Meta描述,我不相信我可以从选项卡数据中获取.
这是我从以下地址获取描述的HTML:
<meta name="description" content="contentstuffya" />
Run Code Online (Sandbox Code Playgroud)
这是我用来在扩展名之外的Javascript:
document.getElementsByName('description')[0].getAttribute('content');
Run Code Online (Sandbox Code Playgroud)
鉴于我拥有的数据,我最好如何做到这一点?
<meta>标签的值只能通过内容脚本读取.这是一个例子:
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
});
Run Code Online (Sandbox Code Playgroud)
在第一行,我找到了<meta name="description">元素.在第二行,content如果元素存在,我会读取其属性的值.
回调chrome.tabs.executeScript接收最后一个表达式的返回值,所以我在代码末尾放置了一个对象文字(用括号括起来).
| 归档时间: |
|
| 查看次数: |
6454 次 |
| 最近记录: |