2012-08-03 138 views
0

我試過環顧Stackoverflow,但找不到任何特別的東西。從Chrome擴展程序的Javascript中獲取標籤網址

所以基本上,我有我的網站共享頁面,是這樣的:

http://domain.com/share.php?link=http://sharing.url 

我的分機是這樣的:

{ 
... 
    "browser_action": { 
    "default_icon": "icon.ico", 
    "default_popup": "schare.html" 
} 
... 
} 

schare.html:

<style> 
body, html{ 
margin:0; 
padding:0; 
} 
iframe{ 
    width:520px; 
    height:200px; 
    margin:0; 
} 
</style> 
<iframe id="iframes" frameborder="0"></iframe> 
<script type="text/javascript" src="popup.js"></script> 

and popup.js:

document.getElementById("iframes").setAttribute("src", "http://domain.com/share.php?link="+location.href+""); 

但這是錯誤的網址。如何在沒有做任何太花哨的事情的情況下獲得標籤網址?

+0

做:'-URL ...? – 2012-08-03 20:12:09

回答

0

您可以通過調用chrome.tabs.query來獲取當前活動的選項卡。回調函數將收到reference to the tab作爲參數。

因此,要獲得當前標籤的網址,你可以使用這個:

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

注意,該getCurrent()方法使用一個回調,所以不要嘗試在一個線性碼使用。

+0

等等...這樣嗎? 'code chrome.tabs.getCurrent(function(tab){ var activeTabUrl = tab.url; }); document.getElementById(「iframes」)。setAttribute(「src」,「http://domain.com/share.php?link=」+ activeTabUrl +「」);' – imp 2012-08-04 10:28:33

+2

getCurrent不會返回當前活動的選項卡,它返回腳本運行的選項卡(考慮到他的腳本在彈出窗口中運行將不確定)。你想要的是查詢當前窗口中的活動標籤,就像這樣...'chrome.tabs.query({active:true,currentWindow:true},function(tab){document.getElementById(「iframes」) .setAttribute(「src」,「http://domain.com/share.php?link=」+ tab.url +「」);});'請用正確的信息更新您的答案,並感謝您的嘗試; – PAEz 2012-08-04 21:25:05

+0

啊,我的壞。對不起,這個錯誤。謝謝,PAEz。 – Fczbkk 2012-08-05 17:18:12

1

如果您在當前窗口中有一組選項卡,而不僅僅是一個,則下面的代碼可能不起作用。下面是修改後的版本,你想與大家分享`鉻擴展

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

相關問題