谷歌浏览器扩展获取页面信息。

12

我正在制作一个Google Chrome扩展程序,需要获取当前页面的URL和标题。如何实现这一点呢?


这个问题已经在这里得到了回答:https://dev59.com/-1TTa4cB1Zd3GeqPpBj4 - Sergey Galchenko
https://dev59.com/g3I-5IYBdhLWcg3wMFMf - Walialu
2个回答

17
chrome.tabs.getSelected(null, function(tab) { //<-- "tab" has all the information
    console.log(tab.url);       //returns the url
    console.log(tab.title);     //returns the title
});

有关更多信息,请阅读chrome.tabs。关于tab对象的内容,请在此处阅读


注意:chrome.tabs.getSelected从Chrome 16开始已被弃用。如文档所建议,应使用chrome.tabs.query()以及参数{'active': true}来选择活动选项卡。

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    tabs[0].url;     //url
    tabs[0].title;   //title
});

对于最近看到这篇文章的任何人,值得指出的是chrome.tabs.getSelected()已被弃用,Konstantin的答案现在是这个问题的正确答案。 - bmelton
请注意,“currentWindow”并不是您可能认为的那个窗口。您很可能想要使用“lastFocusedWindow”,它是当前聚焦的窗口,结合“active”,它是当前聚焦的选项卡。 - V. Rubinetti

7

自Google Chrome 16版本起,方法getSelected()已被弃用(但许多官方文档文章尚未更新)。官方消息在此。要获取指定窗口中所选的标签页,请使用带有参数{'active': true}chrome.tabs.query()。因此现在应该像这样:

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log(tabs[0].url);
  console.log(tabs[0].title);
});

编辑: tabs[0] 是第一个活动选项卡。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接