如何从 Google Chrome 扩展程序获取当前选项卡的 URL? [英] How can I get the URL of the current tab from a Google Chrome extension?
问题描述
我对 Google Chrome 扩展程序很感兴趣,我只想知道如何将当前选项卡的 URL 存储在变量中?
像这样使用chrome.tabs.query()
:
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {让 url = tabs[0].url;//在回调中使用 `url` 因为它是异步的!});
这要求您在扩展中请求访问chrome.tabs
API清单:
权限":[ ...标签"]
请务必注意,当前标签"的定义可能因扩展程序的需要而异.
在查询中设置 lastFocusedWindow: true
是合适的,当您想要访问用户聚焦窗口(通常是最顶部的窗口)中的当前选项卡时.p>
设置 currentWindow: true
允许您在当前正在执行扩展代码的窗口中获取当前选项卡.例如,如果您的扩展程序创建了一个新窗口/弹出窗口(改变焦点),但仍想从运行扩展程序的窗口访问选项卡信息,这可能很有用.
在这个例子中我选择使用 lastFocusedWindow: true
,因为谷歌会调用 currentWindow
可能并不总是存在.
您可以使用此处定义的任何属性自由进一步优化选项卡查询:chrome.tabs.query
I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?
Use chrome.tabs.query()
like this:
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
// use `url` here inside the callback because it's asynchronous!
});
This requires that you request access to the chrome.tabs
API in your extension manifest:
"permissions": [ ...
"tabs"
]
It's important to note that the definition of your "current tab" may differ depending on your extension's needs.
Setting lastFocusedWindow: true
in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).
Setting currentWindow: true
allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.
I chose to use lastFocusedWindow: true
in this example, because Google calls out cases in which currentWindow
may not always be present.
You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query
这篇关于如何从 Google Chrome 扩展程序获取当前选项卡的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!