Get tab url from Chrome Extension in Javascript

霸气de小男生 提交于 2019-12-24 19:24:16

问题


I tried looking around Stackoverflow but couldn't find anything specifically for this.

So basically, I have a share page for my website that goes like this:

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

My extension goes like this:

{
 ...
  "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+"");

But that's the wrong URL. How can I get the tab url in there without doing anything too fancy?


回答1:


The code below may not work if you have an array of tabs in the current window and not just one. Here's a modified version

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




回答2:


You can get the currently active tab by calling chrome.tabs.query. The callback function will receive the reference to the tab as an argument.

So to get the URL of active tab, you can use this:

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

Note, that the getCurrent() method uses a callback, so don't try to use in a linear code.



来源:https://stackoverflow.com/questions/11801845/get-tab-url-from-chrome-extension-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!