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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6871309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:09:53  来源:igfitidea点击:

Google Chrome Extension get page information

javascriptgoogle-chrome-extension

提问by u283863

I'm making a google chrome extension, and I need to get the current page URL and title. How can I achieve this?

我正在制作一个 google chrome 扩展程序,我需要获取当前页面的 URL 和标题。我怎样才能做到这一点?

回答by u283863

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
});

For more please read chrome.tabs. About the tabobject, read here.

更多信息请阅读chrome.tabs。关于tab对象,请阅读此处



Note:chrome.tabs.getSelectedhas been deprecatedsince Chrome 16. As the documentation has suggested, chrome.tabs.query()should be used along with the argument {'active': true}to select the active tab.

注意:自 Chrome 16chrome.tabs.getSelected起已弃用。正如文档所建议的,应该与参数一起使用来选择活动选项卡。chrome.tabs.query(){'active': true}

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

回答by Konstantin Smolyanin

The method getSelected()has been deprecated since Google Chrome 16 (but many articles in the official documentation had not yet been updated). Official message is here. To get the tab that is selected in the specified window, use chrome.tabs.query()with the argument {'active': true}. So now it should looks like this:

该方法getSelected()自 Google Chrome 16 起已被弃用(但官方文档中的许多文章尚未更新)。官方消息在这里。要获取在指定窗口中选择的选项卡,请chrome.tabs.query()与参数一起使用{'active': true}。所以现在它应该是这样的:

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

Edit: tabs[0]is the first active tab.

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