Javascript Chrome 扩展程序:如何从 background.html 获取当前网页 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6451693/
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-08-23 21:47:09  来源:igfitidea点击:

Chrome Extension: How to get current webpage url from background.html

javascripturlgoogle-chrome-extension

提问by Calvin

From my knowledge it is not possible directly by getting tab.url (only possible in the popup.html) and doing message passing also requires that popup.html be open. Is there anyway to bypass this and get the current page url from background.html?

据我所知,无法直接通过获取 tab.url(仅在 popup.html 中可能)并且进行消息传递也需要打开 popup.html。有没有办法绕过这个并从background.html获取当前页面的url?

My best shot was with message passing, which I used this code in background.html

我最好的镜头是消息传递,我在 background.html 中使用了这段代码

var bg = chrome.extension.getPopupPage(); 
var myURL = bg.myURL; 

then in popup.html I had:

然后在 popup.html 我有:

 chrome.tabs.getSelected(null, function(tab) {
    var myURL = tab.url;
})

Anyways the above does't work at all. Anybody know of a way to do this without having to actually open up the popup?

无论如何,以上根本不起作用。有人知道一种无需实际打开弹出窗口即可执行此操作的方法吗?

回答by kirb

chrome.tabs.queryis supported from background pages, of course as long as you have the tabspermission. This is the supported route as of Chrome 19.

chrome.tabs.query后台页面支持,当然只要你有tabs权限。这是 Chrome 19 支持的路由。

chrome.tabs.query({
  active: true,
  currentWindow: true
}, function(tabs) {
  var tab = tabs[0];
  var url = tab.url;
});

Note that currentWindowis needed because it would otherwise return the active tab for everywindow. This should be guaranteed to only return one tab.

请注意,这currentWindow是必需的,否则它会为每个窗口返回活动选项卡。这应该保证只返回一个标签。

Of course, keep in mind that this is an asynchronous API –?you can't access any data it provides except from within the callback function. You can store values (such as urlhere) at a higher scope so another function can access it, but that will still only provide the correct result after the callback is executed.

当然,请记住,这是一个异步 API – 除了在回调函数中之外,您无法访问它提供的任何数据。您可以将值(例如url此处)存储在更高的范围内,以便另一个函数可以访问它,但这仍然只能在执行回调后提供正确的结果。



(The below is my original answer kept for posterity –?this method is no longer necessary, requires an always-running background page, and getSelected()is deprecated.)

(以下是我为后代保留的原始答案 -?此方法不再需要,需要始终运行的后台页面,并且getSelected()已弃用。)

First put this in background.html and make the myURL variable global:

首先将其放入 background.html 并使 myURL 变量成为全局变量:

var myURL = "about:blank"; // A default url just in case below code doesn't work
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked 
    chrome.tabs.getSelected(null, function(tab) {
        myURL = tab.url;
    });
});

Then run this in popup.html when you want to get the page url:

然后在想要获取页面 url 时在 popup.html 中运行它:

chrome.extension.getBackgroundPage().myURL;

So if I were to make that appear inside the popup and I went to Google and clicked your page or browser action, I'll see http://google.com/webhpin the popup.

因此,如果我想让它出现在弹出窗口中,然后我去谷歌并点击您的页面或浏览器操作,我会http://google.com/webhp在弹出窗口中看到。

回答by Siva Tumma

Upon seeing this post I felt that there should be a way to mark a discussion as "obsolete".

看到这篇文章后,我觉得应该有一种方法可以将讨论标记为“过时”。

Reasons being...

原因是...

This question needs to migrate to manifest v2 and...
The answers both are not working. I am using a select onchange and posting the current tab's url which is not working.

这个问题需要迁移到 manifest v2 和...
答案都不起作用。我正在使用 select onchange 并发布当前选项卡的 url,但它不起作用。

Might be these all worked in manifest v1.

可能这些都适用于清单 v1。

My answer is ...

我的回答是...

var myURL = "not set yet";
window.addEventListener('load', function () {
    chrome.tabs.getSelected(null,function(tab){
        myURL=tab.url;
    });     

回答by viclm

chrome.tabs.getSelected(null, function(tab) {
  var myURL = tab.url;
});

I don not understand, the code above can be used in background page to get the current tab's url.

我不明白,上面的代码可以在后台页面中使用以获取当前选项卡的网址。

回答by mhipp588

This is a little more work but works like a charm...

这是一个多一点的工作,但就像一个魅力......

I would use a content script; it's relatively simple & allows you to get any info from current page you might want. Have the background page "inject" the script into the current webpage to gather the info you need. The script then just passes it back to the background.

我会使用内容脚本;它相对简单,并允许您从当前页面获取您可能想要的任何信息。让后台页面将脚本“注入”到当前网页中以收集您需要的信息。然后脚本只是将它传递回后台。

background.js:

背景.js:

// Icon is clicked and triggers content script to be injected into current webpage
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, { file: 'inject.js' });
});

// Listens for message back from content script and then runs
chrome.runtime.onMessage.addListener(function (request) {
    var URL = request.url;
});

inject.js (content script):

注入.js(内容脚本):

// Gathers up in the information that you need from webpage
var pageInfo = {
  "url": window.location.href
};

// Sends the information back to background.js
chrome.runtime.sendMessage(pageInfo);

Hope this helps someone!

希望这可以帮助某人!