【问题标题】:Chrome Web Extension, using buttons to open web page in new tabChrome Web 扩展,使用按钮在新标签页中打开网页
【发布时间】:2018-09-17 22:43:02
【问题描述】:

我是第一次开发 chrome 扩展。它相对简单,我要做的就是在单击按钮时在新选项卡中打开一个网页。但是,我不确定如何在没有 javascript 的情况下执行此操作,因为我知道 chrome 块内联 <script> 元素(或类似的东西)。下面是我的popup.html

<!DOCTYPE html>
<html>
<head>


<style>

.button {
    position: relative;
    background-color: #4F5B62;
    border: none;
    font-size: 28px;
    font-family: "Roboto Mono";
    font-weight: lighter;
    color: #FFFFFF;
    opacity: 0.6;
    padding: 20px;
    width: 200px;
    text-align: center;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    text-decoration: none;
    overflow: hidden;
    cursor: pointer;
    border-radius: 12px;
}

.button:hover{
  opacity: 1;
}

.button:after {
    content: "";
    background: #f1f1f1;
    display: block;
    position: absolute;
    padding-top: 300%;
    padding-left: 350%;
    margin-left: -20px !important;
    margin-top: -120%;
    opacity: 0;
    transition: all 0.8s
}

.button:active:after {
    padding: 0;
    margin: 0;
    opacity: 1;
    transition: 0s
}

body{
  background-color: #263238;
}

head{
  background-color: #263238;
}
</style>
</head>
<body>


<button type="button" class="button">Access chatter</button>

</body>
</html>

任何帮助将不胜感激。

【问题讨论】:

  • 只需使用单独的 popup.js 文件和 src 属性:&lt;script src="popup.js"&gt;&lt;/script&gt;
  • 像这样?
  • 将您的 JavaScript 放在一个单独的文件中,并使用 script 标记将该文件包含在 popup.html 中,例如 &lt;script src="popup.js"&gt;&lt;/script&gt;documentation 中有示例
  • @tomclack 内联 javascript 不允许在 Chrome 扩展中使用。

标签: javascript html json google-chrome google-chrome-extension


【解决方案1】:

manifest.json

首先您需要在manifest.json 中添加使用chrome.tabs API 的权限。

{
   ...
   "permissions": ["tabs"],
   ...
}

popup.html

然后你可以在你的按钮和popup.js 脚本在你的&lt;body&gt; 标签底部添加一个id。

<body>
   <button type="button" class="button" id="btn1">Access chatter</button>
   <script src="popup.js"></script>
</body>

popup.js

最后在你的脚本中添加按钮动作。

使用原生 JavaScript

var button = document.getElementById("btn1");
button.addEventListener("click", function(){
    chrome.tabs.create({url:"http://www.google.com/"});
});

使用 jQuery

如果使用jQuery一定要在popup.js上面添加相应的脚本。

$('#btn1').click(function() {
   chrome.tabs.create({url:"http://www.google.com/"});
});

【讨论】:

  • 为了使用 jQuery,您必须在 popup.js 上方使用另一个 script 标记来包含 jQuery javascript 文件。
【解决方案2】:

您可以在此处阅读有关 Chrome 扩展入门 https://developer.chrome.com/extensions/getstarted

在这里你可以看到创建新标签的参考https://developer.chrome.com/extensions/tabs#method-create

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2013-05-06
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多