创建一个Chrome扩展,有按钮链接到网站

Creating a Chrome Extension that has button links to websites

本文关键字:按钮 链接 网站 扩展 Chrome 一个 创建      更新时间:2023-09-26

我已经为一个扩展编写了代码,应该启动给定的网站和HTML文件时启动工作正常;然而,当我点击扩展,按钮不做任何事情。

<!doctype html>
<html>
<head>
<title>Google Apps Launcher</title>
<script src="popup.js"></script>
</head>
<body>
<h1>Google Apps Launcher</h1>
<FORM>
    <INPUT Type="BUTTON" Value="Gmail" Onclick="window.location.href='https://www.gmail.com'"> 
    <INPUT Type="BUTTON" Value="Google Drive" Onclick="window.location.href='https://drive.google.com/drive/u/0/'"> 
    <INPUT Type="BUTTON" Value="Google Calendar" Onclick="window.location.href='https://calendar.google.com/calendar/render#main_7'"> 
    <INPUT Type="BUTTON" Value="Google Docs" Onclick="window.location.href='https://docs.google.com/document/u/0/'"> 
<FORM/>
</body>
</html>

首先,请通过学习如何调试扩展弹出窗口来帮助自己。它包括右键单击按钮并选择检查弹出

如果你这样做了,你会看到的第一个东西是这样的:

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:" script-src 'self' chrome-extension-resource:"。启用内联执行需要'unsafe-inline'关键字、散列('sha256-…')或nonce ('nonce-…')。

这是因为Chrome对扩展的限制性内容安全策略不允许在HTML本身中设置带有文本字符串的点击处理程序。有关更多信息,请参阅Chrome扩展中不工作的onClick。

那么,您的处理程序试图实现什么?如果您在弹出窗口中单击此按钮,则window指的是弹出窗口本身。我怀疑你是否想要在弹出窗口中加载上述网站,你可能想要打开一个新的选项卡。我不认为你可以把弹出窗口本身导航到外部网站。

你有一个选择来解决这个问题:

  1. 阻力最小的路径是使用纯HTML链接而不是JS:

    <a href="https://www.gmail.com" target="_blank">Gmail</a>
    

    你可以给这个<a>元素设置你想要的样式-它可以看起来像一个按钮。

  2. 如果你特别想要<input type="button">元素,你需要按照popup.js中的"click"事件使用addEventListener的标准程序。参见CSP文档和上面链接的onClick问题-以及其他答案中的代码。

    你会想用chrome.tabs.create代替在新标签页中打开链接,例如:

    chrome.tabs.create({url: "https://gmail.com"});
    

    请参阅此问题:打开新选项卡而不会失去弹出焦点

您需要设置事件侦听器。像这样:

document.querySelectorAll('INPUT[Type="BUTTON"]').forEach(button =>
  button.addEventListener('click', event => {
    window.location.href = event.target.dataset.location
  })
)
<!doctype html>
<html>
<head>
<title>Google Apps Launcher</title>
<script src="popup.js"></script>
</head>
<body>
<h1>Google Apps Launcher</h1>
<FORM>
    <INPUT Type="BUTTON" Value="Gmail" data-location="https://www.gmail.com"> 
    <INPUT Type="BUTTON" Value="Google Drive" data-location="https://drive.google.com/drive/u/0/"> 
    <INPUT Type="BUTTON" Value="Google Calendar" data-location="https://calendar.google.com/calendar/render#main_7"> 
    <INPUT Type="BUTTON" Value="Google Docs" data-location="https://docs.google.com/document/u/0/"> 
<FORM/>
<!-- insert script file, with content from JavaScript section -->
      
</body>
</html>

你的代码有味道。考虑一下谷歌风格指南中的这些章节:

  • 资本化
  • Intendation
  • 使用a标签代替javascript进行导航