简体   繁体   English

如何使用 javascript 在我的 chrome 扩展程序中获取当前选项卡的 URL

[英]How to fetch URL of current Tab in my chrome extension using javascript

I am just getting started with Google Chrome Extension development and my project involves making an extension which when clicked prints the URL of whichever page/tab is currently open.我刚刚开始使用 Google Chrome 扩展程序开发,我的项目涉及制作一个扩展程序,单击该扩展程序会打印当前打开的任何页面/选项卡的 URL。

So if I am on google's home page and I click my extension, I need to get " https://www.google.com/ " as my output within the extension.因此,如果我在 google 的主页上并单击我的扩展程序,我需要在扩展程序中将“ https://www.google.com/ ”作为我的 output。

I need to do this using javascript and am unable to find code which I understand and which does the job.我需要使用 javascript 来执行此操作,但无法找到我理解的代码和完成工作的代码。 I read about using "window.location" and "document.href" and stuff but won't that give me the url of just my extension and not the current tab?我阅读了有关使用“window.location”和“document.href”之类的内容,但这不会给我 url 的只是我的分机而不是当前选项卡吗?

Please help me get started.请帮助我开始。 Thanks in advance.提前致谢。

Try尝试

chrome.tabs.getCurrent(function(tab){
        console.log(tab.url);
});

Note you must have the tabs permission set in your manifest file请注意,您必须在清单文件中设置tabs权限

"permissions": [
    "tabs"
],

http://developer.chrome.com/extensions/tabs.html http://developer.chrome.com/extensions/tabs.html

or the activeTab permission if initiated by a click on the extension button[ Xan ]activeTab权限,如果通过单击扩展按钮 [ Xan ] 启动

https://developer.chrome.com/extensions/activeTab https://developer.chrome.com/extensions/activeTab


If the above doesn't work try如果上述方法不起作用,请尝试

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

Using javascript, it will work if you are not using it in popup because javascript in popup will return url of popup therefore, in popup, you have to use Chrome tab API and set permission in Chrome manifest.使用 javascript,如果您不在弹出窗口中使用它,它将起作用,因为弹出窗口中的 javascript 将返回弹出窗口的 url,因此,在弹出窗口中,您必须使用 Chrome 选项卡 API 并在 Chrome 清单中设置权限。

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

So best way is to use Chrome tab API所以最好的方法是使用 Chrome tab API

You need to be careful with what you mean by "current tab".您需要注意“当前选项卡”的含义。 If the user has more than one window open, each of them with multiple tabs, Chrome defines the "current window" as the one that is running the content script that makes use of the chrome.tabs API .如果用户打开了多个窗口,每个窗口都有多个选项卡, Chrome 会将“当前窗口”定义为运行使用chrome.tabs API 的内容脚本的窗口 That happened to me and I solved it by referencing not the "current" window but the last focused one :这发生在我身上,我通过引用不是“当前”窗口而是最后一个焦点窗口来解决它:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
});

References:参考:

https://developer.chrome.com/extensions/windows#current-window https://developer.chrome.com/extensions/tabs#method-query https://developer.chrome.com/extensions/windows#current-window https://developer.chrome.com/extensions/tabs#method-query

Hope it helps!希望能帮助到你!

DO NOT use getSelected不要使用getSelected

As per the Chrome Developer Docs : chrome.tabs.getSelected has been deprecated since Chrome ver.33根据Chrome 开发人员文档chrome.tabs.getSelected自 Chrome ver.33 起已被弃用

Instead use:而是使用:

chrome.tabs.query({active:true}, __someCallbackFunction__) like Musa's second suggestion. chrome.tabs.query({active:true}, __someCallbackFunction__)喜欢穆萨的第二个建议。

UPDATE: this method is now deprecated, so please don't use it更新:此方法现已弃用,因此请不要使用它

In my case any above has not worked.就我而言,以上任何一项都不起作用。 So I used this:所以我用了这个:

chrome.tabs.getSelected(null, function(tab) {
    console.log(tab.url)
})

and it worked great!效果很好! Hope it helps.希望能帮助到你。

this worked for me give it a try这对我有用试一试

chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
 });

Here is the answer your looking for without adding new tabs permissions这是您在不添加新tabs权限的情况下寻找的答案

chrome.browserAction.onClicked.addListener(function(e){
     console.log(e.url); 
     //give you the url of the tab on which you clicked the extension
})

The solutions posted here somehow did not worked for me but below snippet worked without any issues-此处发布的解决方案不知何故对我不起作用,但以下代码段没有任何问题-

let currentURL = window.location.href;
console.log(currentURL)

Please be aware that chrome.tabs.query() and chrome.tabs.getCurrent will run into race conditions when called in short order from multiple content scripts.请注意chrome.tabs.query()chrome.tabs.getCurrent在从多个内容脚本以短顺序调用时会遇到竞争条件。

The returned tab will not necessarily be the tab of the requestor.返回的选项卡不一定是请求者的选项卡。

An easier way to do this is to send a message to the background thread.一种更简单的方法是向后台线程发送消息。 This message includes the sending tab as the tab parameter.此消息包括发送选项卡作为tab参数。

The background thread can take this parameter and directly include it in its response to the message.后台线程可以使用此参数并将其直接包含在其对消息的响应中。

Not only does this prevent race conditions, it's also faster because it does not use an asynchronous operation (unlike the call to chrome.tabs.query() )这不仅可以防止竞争条件,而且速度更快,因为它不使用异步操作(与调用chrome.tabs.query()

Example:例子:

Content script内容脚本

var myTab;
chrome.runtime.sendMessage({ message: "get_tab_msg" }, (response) => {
    myTab = response.tab;
});

Background script后台脚本

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.message === "get_tab_msg") {
        // The content script has asked for the tab.
        sendResponse({tab: sender.tab});
    }
});

Update : If you are on manifest version 3 then proceed with the following,更新:如果您使用的是清单版本 3,请继续执行以下操作,

 async function getCurrentTab() {
 let queryOptions = { active: true, currentWindow: true };

  let [tab] = await browser.tabs.query(queryOptions);
  localStorage.setItem('tabname' , tab);
   return tab;
  }

 getCurrentTab()
 .then((data) => { console.log('newdata',data)})
 .then(() => { console.log('error')});

JS:记者:

let myLocationUrl = location.href;

console.log(myLocation);

The simplest method: 最简单的方法:

console.log('current url' + window.location) console.log('当前URL'+ window.location)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在javascript(chrome扩展名)中获取选项卡或窗口的当前URL - How to get the current URL of a tab or a window in javascript(chrome extension) 使用 Javascript 单击 chrome 扩展中的按钮后,将当前选项卡 URL 更改并打开其他选项卡 - Change and open current tab URL to something else after clicking a button in chrome extension using Javascript 如何在chrome中复制/获取当前标签页网址并在弹出窗口中输出? - How to copy/fetch current tab url in chrome and output in popup? 如何在 Chrome 扩展程序中重定向当前标签的 url? - How to redirect current tab's url in Chrome extension? 提取当前网址并以Chrome扩展名保存 - Fetch current URL and save it with a chrome extension 将当前标签页的网址发送到弹出窗口-Chrome扩展程序 - Send the URL of current tab to popup - Chrome extension 如何使用 Chrome 扩展程序关闭当前的 Chrome 选项卡? - How to close the current Chrome tab with a Chrome Extension? 从JavaScript的Chrome扩展程序中获取标签网址 - Get tab url from Chrome Extension in Javascript Chrome扩展程序可复制当前网址并打开标签以执行操作 - Chrome extension to copy current URL and open tab to perform actions 获取chrome扩展名的当前(活动)标签的网址 - get url of current (active) tab for chrome-extension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM