创建具有指向网站按钮链接的Chrome扩展程序

时间:2016-10-26 11:19:48

标签: javascript google-chrome-extension

我已经编写了一个扩展程序的代码,该扩展程序应该启动给定的网站,并且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>

2 个答案:

答案 0 :(得分:2)

首先,请了解如何通过学习how to debug extension popups来帮助自己。它包括右键单击按钮并选择 Inspect popup

如果你这样做,你会看到的第一件事就是这样:

  

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:&#34; script-src&#39; self&#39;铬扩展资源:&#34 ;. “不安全 - 内联”和“不安全”。关键字,哈希(&#39; sha256 -...&#39;)或nonce(&#39; nonce -...&#39;)是启用内联执行所必需的。

这是因为Chrome的限制性Content Security Policy for extensions不允许使用HTML本身的一串文字设置点击处理程序。有关详细信息,请参阅onClick within Chrome Extension not working

此外,你的处理程序试图实现什么?如果在弹出窗口中单击此按钮,window将引用弹出窗口。我怀疑你想在弹出窗口中加载所述网站,你可能想要打开一个新标签。我不认为您可以将弹出窗口本身导航到外部网站。

您可以选择修复此问题:

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

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

    然后您可以根据需要设置此<a>元素的样式 - 它可以看起来像一样按钮。

  2. 如果您特别需要<input type="button">元素,则需要使用addEventListener"click"中的popup.js个事件执行标准流程。请参阅CSP文档和上面链接的onClick问题以及the other answer中的代码。

    您希望使用chrome.tabs.create来打开新标签中的链接,例如:

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

    另请参阅此问题:Open new tab without losing popup focus

答案 1 :(得分:1)

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

&#13;
&#13;
document.querySelectorAll('INPUT[Type="BUTTON"]').forEach(button =>
  button.addEventListener('click', event => {
    window.location.href = event.target.dataset.location
  })
)
&#13;
<!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>
&#13;
&#13;
&#13;

你的代码闻起来对我来说。请参阅Google样式指南中的以下部分: