arp
arp

Reputation: 1368

How to copy/fetch current tab url in chrome and output in popup?

I am trying my hands on creating a google chrome extension.I am trying to set innerHTML of < H4 >(in popup.html) to current tab url.Also,console.log doesnt print anything in console.

This is my manifest.json

{
  "name": "Hello World!",
  "version":"1.1",
  "manifest_version": 2,
  "description": "My first Chrome extension.",
  "permissions":["tabs"],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

This is my popup.html

<body style="width:450px;height:150px">
<script type="text/javascript" src="popup.js" ></script>
<h1>Hello World!</h1>
<h2>This is my first chrome extension.</h2>
<h3>Hope you love it.</h3>
<h4 id="url"></h4>
</body>

This is popup.js -

//chrome.browserAction.onClicked.addListener(function(tab)
//{     
    /*console.log("papaya");
    var encoded_url = encodeURIComponent(tab.url);
    var urlObj = document.getElementById("url");
    urlObj.innerHTML = encoded_url;*/

    chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    console.log(tabs[0].url);
});

//});

Upvotes: 0

Views: 1387

Answers (2)

arp
arp

Reputation: 1368

I did it.

added "background":["popup.js"], line in manifest.json

and modified my popup.js

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    var tab_url = tabs[0].url;
    console.log(tab_url);
    var urlObj = document.getElementById("url");
    urlObj.innerHTML = tab_url;
});

Upvotes: 1

user3307259
user3307259

Reputation:

encodeURICompenent should be encodeURIComponent

and as it is now, your chrome.tabs.query is fired on start of the session
(button on click is commented out)

edit:
and as Parag Gangil stated, that log will be in background page of your extension, not the current (web) page you are opened
either go to chrome://extensions and click on background page of your extension >> console, or right click on toolbar icon "inspect popup"

Upvotes: 0

Related Questions