2016-10-26 138 views
-3

我已经编写了扩展的代码,该扩展在启动时可以启动给定的网站和HTML文件;不过,当我点击扩展名时,按钮不会做任何事情。创建一个Chrome扩展,其中包含指向网站的按钮链接

<!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> 
+0

你会如何建议我这样做呢? – cwittenb

回答

1

您需要设置事件侦听器。事情是这样的:

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>

你的代码味道对我来说。考虑从谷歌风格指南以下部分:

+0

这些可能是基本问题,但“document.query ...”部分去哪里?在Manifest中?并且不会有任何JavaScript需要在background.js文件中? – cwittenb

+0

其追加到'popup.js'和移动''到页面底部 – terales

2

首先,请学习如何通过学习how to debug extension popups帮助自己。它包括右键单击该按钮并选择检查弹出式菜单

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

拒绝,因为它违反了以下内容安全策略指令执行内嵌脚本:“脚本的src‘自我’铬扩展资源”。 “内联不安全”关键字,散列('sha256 -...')或一个随机数('nonce -...')是启用内联执行所必需的。

这是因为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">元素,你需要按照你的popup.js使用addEventListener"click"事件的标准程序。请参阅CSP文档和上面链接的onClick问题 - 以及the other answer中的代码。

    您需要使用chrome.tabs.create,而不是打开新的标签页的链接,例如:

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

    也看到这个问题:Open new tab without losing popup focus

+2

你可以把'button'或'input'里面'了'... – wOxxOm

相关问题