简体   繁体   中英

Chrome extension active tab and console.log

This is my first chrome extension and I just want to start with a simple thing: grabbing the url and showing it in console.log(). The problem is when I click that button, nothing is logged.

manifest.json

{
  "manifest_version": 2,

  "name": "Copy Title and URL",
  "description": "This extension will copy the title and url of an article",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab"
   ]
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Copy Title & URL</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <button id="copyUrl">Copy Title + URL</button>
  </body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
  var copyURLButton = document.getElementById('copyUrl');
  copyURLButton.addEventListener('click', function() {
    chrome.tabs.getSelected(null, function(tab) {
      console.log(tab.url);
    });
  }, false);
}, false);

Any idea what I'm doing wrong here?

Thanks.

Probably the console you're looking in is wrong, as your code seems fine (except for using deprecated getSelected() , you should switch to query() )

To access the popup's console, you need to right-click your extension's button and select "Inspect popup".

Awesome, I seem to have been looking at the wrong console. I changed the code to query below.

document.addEventListener('DOMContentLoaded', function() {
  var copyURLButton = document.getElementById('copyUrl');
  copyURLButton.addEventListener('click', function() {
    chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
      console.log(tabs[0].url);
    });
  }, false);
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM