You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展开发求助:点击图标时打开当前页URL并在弹窗显示

我来帮你完成这个Chrome扩展的功能,咱们一步步来实现:点击扩展图标时,打开当前页面URL的新窗口,同时在扩展的弹窗里显示这个URL。

1. 先配置 Manifest 核心文件

Chrome扩展必须依赖manifest.json来声明权限和基础配置,这里我们需要添加标签页访问权限和弹窗入口:

{
  "manifest_version": 3,
  "name": "当前URL新窗口 opener",
  "version": "1.0",
  "description": "点击扩展图标,在新窗口打开当前页面URL并显示",
  "permissions": ["tabs"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon16.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  }
}

注:你可以准备几个不同尺寸的图标替换路径,暂时忽略图标也能正常测试功能。

2. 编写弹窗页面(popup.html)

这个页面是点击扩展图标后弹出的窗口,我们需要一块区域来展示当前页面的URL:

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      width: 300px;
      padding: 15px;
      font-family: Arial, sans-serif;
    }
    #urlDisplay {
      margin-top: 10px;
      padding: 8px;
      background: #f0f0f0;
      border-radius: 4px;
      word-break: break-all;
    }
  </style>
</head>
<body>
  <h3>当前页面URL:</h3>
  <div id="urlDisplay"></div>
  <script src="popup.js"></script>
</body>
</html>
3. 完成功能逻辑代码(popup.js)

我把你提供的代码补全,实现获取当前URL、弹窗显示、打开新窗口三个核心功能:

document.addEventListener('DOMContentLoaded', function() {
  // 获取当前活跃标签页的URL
  chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function(tabs) {
    const currentUrl = tabs[0].url;
    const urlDisplay = document.getElementById('urlDisplay');
    
    // 在弹窗中显示URL
    urlDisplay.textContent = currentUrl;
    
    // 在新窗口打开这个URL
    chrome.windows.create({url: currentUrl});
  });
});

如果你更希望点击弹窗内的按钮才触发功能(而不是弹窗加载时自动执行),可以修改成下面的版本:

document.addEventListener('DOMContentLoaded', function() {
  const checkPageButton = document.getElementById('checkPage');
  
  checkPageButton.addEventListener('click', function() {
    chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function(tabs) {
      const currentUrl = tabs[0].url;
      const urlDisplay = document.getElementById('urlDisplay');
      
      urlDisplay.textContent = currentUrl;
      chrome.windows.create({url: currentUrl});
    });
  });
});

对应的popup.html需要添加按钮:

<button id="checkPage">打开新窗口并显示URL</button>
测试方法
  • 把manifest.json、popup.html、popup.js放在同一个文件夹里
  • 打开Chrome浏览器,输入chrome://extensions/进入扩展管理页
  • 开启「开发者模式」,点击「加载已解压的扩展程序」,选择你的文件夹
  • 现在点击扩展栏里的图标,就能看到弹窗显示当前URL,同时新窗口打开该页面了!

内容的提问来源于stack exchange,提问作者Tejas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:37:51