2017-03-26 29 views
1

我想要获取URL以在扩展名为chrome的变量中使用它。 我在这里读到这段代码:如何在活动选项卡中获取URL并在变量中使用它

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

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" 
    } 
} 

我不明白的地方我做一个错误...

(对不起,我的英文不好...)

+1

右键单击弹出框,然后“检查”,你会看到控制台。另外,确保只在回调中使用变量作为chrome。* API是异步的。 – wOxxOm

+0

@wOxxOm 好的,谢谢,我现在没有rightclik - >检查... 它工作正常;) 但如果我想利用变量tabURL后? 我需要将脚本popup.js的var url链接到脚本的var tabURL background.js – GeGaX

+0

您想将您的变量传递给背景页面吗?你需要使用消息传递:https://developer.chrome.com/extensions/messaging – OriEng

回答

2

行,所以我给你写了完整的解决方案,以获得popup.js的活动网址:

manifest.json的:

{ 
    "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页面中获取这个变量。现在你可以对这个变量做任何你想做的事情。

祝你好运!

+0

非常感谢! 我测试今晚;) – GeGaX

+0

它的工作完美;))再次感谢OriEng,一个问题......这是一个“通用”的代码?我可以使用它的所有(获取网址)? – GeGaX

+0

@GeGaX乐意帮忙!在这种情况下,“通用”是什么意思?它现在适用于所有网址,但只需更改清单中的“匹配”即可更改它。 – OriEng

相关问题