【问题标题】:Get tab url from Chrome Extension in Javascript从 Javascript 中的 Chrome 扩展程序获取标签页 url
【发布时间】:2012-08-03 19:08:36
【问题描述】:

我尝试查看 Stackoverflow,但找不到专门针对此的任何内容。

所以基本上,我的网站有一个共享页面,如下所示:

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>

和popup.js:

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

但那是错误的 URL。我怎样才能在不做任何花哨的事情的情况下获得标签网址?

【问题讨论】:

  • 你想分享一个chrome-extension:-URL...吗?

标签: javascript google-chrome google-chrome-extension popup


【解决方案1】:

如果您在当前窗口中有一组选项卡,而不仅仅是一个,则下面的代码可能不起作用。这是修改后的版本

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

【讨论】:

    【解决方案2】:

    您可以通过调用chrome.tabs.query 来获取当前活动的标签。回调函数将接收reference to the tab 作为参数。

    所以要获取活动标签的 URL,你可以使用这个:

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

    注意,getCurrent() 方法使用回调,所以不要尝试在线性代码中使用。

    【讨论】:

    • 等等...这样吗? code chrome.tabs.getCurrent(function (tab) { var activeTabUrl = tab.url; }); document.getElementById("iframes").setAttribute("src", "http://domain.com/share.php?link="+activeTabUrl+"");
    • getCurrent 不返回当前活动的选项卡,它返回运行脚本的选项卡(考虑到他的脚本在弹出窗口中运行将是未定义的)。您想要的是在当前窗口中查询活动选项卡,如下所示...chrome.tabs.query({active:true,currentWindow:true},function(tab){document.getElementById("iframes").setAttribute("src", "http://domain.com/share.php?link="+tab.url+"");}); 请使用正确的信息更新您的答案,感谢您的尝试;)
    • 啊,我的错。对不起这个错误。谢谢,PAEz。
    • 我尝试了这段代码(复制粘贴),但当脚本从弹出窗口运行时仍然未定义:(
    • 不要忘记在你的manifest中添加"permissions": [ "tabs", "http://*/*" ],否则url字段将是未定义的
    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    相关资源
    最近更新 更多