Chrome 扩展,chrome.tabs.query 的结果未定义

Chrome Extension, result of chrome.tabs.query is undefined

我是一个 HTML/Javascript 新手,正在尝试创建一个简单的浏览器操作" chrome 扩展。我花了几个小时试图让它的一部分工作。当弹出窗口打开时,一个存在称为 "myBtn" 的按钮,当单击 ID 为 "Demo" 的元素时,应该从文本更改为 innerHTML,即当前选项卡 Url。我已经设法做到了单击按钮后,默认文本将替换为 "undefined"。我为解决此问题所做的每项更改似乎都让我倒退。我已经阅读了该网站和其他网站上的许多帖子,但无法解决。任何人都看到我的代码中的错误阻止 Url 播放?

我在清单中拥有 "tabs" 和 "activeTab" 权限。相关代码是:

"manifest_version": 2,
"name": "Sample",
"description": "This extension launches Form on current page",
"version": "1.0",

"icons": { "128": "ITVCicon128x128.png" },

"browser_action": {
"default_icon": "ITVCicon.png",
"default_popup": "popup.html"
 },
"permissions": [
      "tabs",
  "activeTab",
      "https://ajax.googleapis.com/"

Popup.html 是:

<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p> click the button to get the current tab URL for cut/paste  <button
id="myBtn"> Try it</button> </p>
<p id="demo">Url displays Here</p>
<script src="popup.js"></script>
</body>
</html>

包含函数的 popup.js 是:

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

document.getElementById("myBtn").addEventListener("click", geturl);

我修改了你的 popup.js 并使用 DOMContentLoaded 作为 Chrome 扩展建议,如:

popup.js:

function geturl() {
  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
  var tabURL = tabs[0].url;
     document.getElementById("demo").innerHTML = tabURL; //The line I changed to pass the URL to html.
   });
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("myBtn").addEventListener("click", geturl);
});

因此您不必将 popup.js 放在 popup.html 正文的末尾。我改成:

popup.html:

<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<h1>My Web Page</h1>
<p> click the button to get the current tab URL for cut/paste  
<button id="myBtn"> Try it</button> </p>
<p id="demo">Url displays Here</p>
</body>
</html>

最后,我测试了它对我有用。