Google chrome extension 如何在活动选项卡中获取URL并在变量中使用它

Google chrome extension 如何在活动选项卡中获取URL并在变量中使用它,google-chrome-extension,Google Chrome Extension,我想获取url,以便在带有chrome扩展名的变量中使用它。 我在这里读到了这个代码: chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) { var tabURL = tabs[0].url; console.log(tabURL); }); 但它在这个url上不起作用 http://sail.zezo.org/clipperton-noumea/chart.pl

我想获取url,以便在带有chrome扩展名的变量中使用它。 我在这里读到了这个代码:

   chrome.tabs.query({
    active: true,
    currentWindow: true
}, function(tabs) {
    var tabURL = tabs[0].url;
    console.log(tabURL);
});
但它在这个url上不起作用

http://sail.zezo.org/clipperton-noumea/chart.pl?lat=-15.93361&lon=-176.0022&userid=1577252 我不明白我在哪里犯了错误


(很抱歉我的英语不好…

好的,我给你写了一个完整的解决方案来获取popup.js中的活动url:

manifest.json:

{
  "manifest_version": 2,

  "name": "Route zezo.org",
  "version": "1.0",
  "description": "Extraire la route proposée",
  "permissions": [
    "http://sail.zezo.org/*",
    "tabs"
  ],
  "icons": {    
        "16": "icon-16.png",
        "48": "icon-48.png",
        "128": "icon-128.png"
  },    
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }  
}
{
  "manifest_version": 2,
  "name": "Route zezo.org",
  "version": "1.0",
  "description": "Extraire la route proposée",
  "permissions": [
  "http://sail.zezo.org/*",
  "tabs"
   ],
   "content_scripts": [
    {
     "matches": ["http://*/*", "https://*/*"],
     "js": ["content.js"],
     "run_at": "document_end"
    }],
   "icons": {    
      "16": "icon-16.png",
      "48": "icon-48.png",
      "128": "icon-128.png"
       },    
   "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
   "background": {
     "scripts": ["background.js"]
  }

}
popup.js

window.onload=function(){
  chrome.runtime.getBackgroundPage(function(backgroundPage){ 
  var currentUrl = backgroundPage.tabURL;
  //Use the url ........
  console.log(currentUrl);

 })

};
background.js

var tabURL = ""; 
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {

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

     });
    }
  );
content.js

chrome.runtime.sendMessage("send");
其思想是:您的扩展在您放入清单中“匹配项”的任何url中运行。内容脚本将消息发送到您想要获取此url的后台页面,后台页面获取消息并将其设置在变量中,然后您在popup.js页面中获取此变量。现在你可以用这个变量做任何你想做的事情


祝你好运

右键单击弹出窗口,然后检查,您将看到控制台。另外,请确保仅在回调中使用变量作为chrome.*API是异步的。@wOxxOm好的,谢谢,我现在没有右键单击->检查。。。它工作得很好;)但是如果我想利用变量tabURL after?我需要将script popup.js的var url链接到script background.js的var tabURL您想将变量传递到后台页面吗?您需要使用消息传递:否,我想将background.js中的变量传递给popup.js,但我想可能与chrome.runtime.getBackgroundPage()相同,我在background.js
chrome.tabs.query中只有这个变量({active:true,currentWindow:true},function(tabs){var tabURL=tabs[0].url;})非常感谢!我今晚测试这个;)它工作得很好再次感谢OriEng,一个问题。。。这是一个“通用”代码?我可以全部使用它(获取url)?@GeGaX很乐意帮助!在这种情况下,你所说的“通用”是什么意思?它现在适用于每个url,但您可以通过更改清单中的“匹配项”来更改它。“通用”在代码不变的意义上,它可以应用于任何地方(我把它放在手肘下,再次感谢您);)