2012-08-03 144 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; });

相关问题