如何将点击事件添加到Chrome扩展程序中的按钮?

时间:2016-06-05 16:01:41

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

我正在尝试创建一个非常简单的Chrome扩展程序,打开LinkedIn的多个标签,搜索我输入的不同关键字。

由于这是我的第一个扩展程序,因此我的大多数代码都基于this extension,这与我的想法非常相似。

问题是当我点击“搜索”按钮时,没有任何反应。我刚开始编码一周,所以我非常感谢任何帮助!

除了知道代码有什么问题外,在这种情况下还需要一个后台脚本吗?

谢谢!

以下是我的代码:

Manifest.json

{
"manifest_version": 2,
"name": "Search Assistant",
"description": "This extension makes LinkedIn Search easy.",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},

"content_scripts": [
{
  "matches": ["http://*/*", "https://*/*"],
  "js": ["myscript.js"]
}
],
"chrome_url_overrides" : {
"newtab": "newtab.html"
},

"background": {
"scripts": ["bg.js"]
}


}

Popup.html

<!doctype html>
<head>

<style type="text/css">
body{
font family: Helvetica, Arial, sans;
font-size: 12px;
}
#instruction{
    padding-bottom: 10px;
}
#searcharea{
    padding-bottom: 10px;
}
#search{
    padding-bottom: 10px;
    float: left;
}
#companies{
    white-space: nowrap;
    overflow:auto;
}
</style>
<style type="text/javascript" src="popup.js"></style>

</head>

<body>

<div id="instruction">Companies you want to search for:</div>
<div id="searcharea"><textarea rows="20" cols="80" id="companies" wrap="soft" tabindex="1"></textarea></div>

<div id="search">
<button id="btn1" tabindex="2">Search</button>
</div>

<p id="demo"></p>

</body>
</html>

Popup.js

document.addEventListener('DOMContentLoaded', function (){
    document.getElementById('btn1').addEventListener('click', loadSites);
    document.getElementById('companies').focus();
});

function loadSites(e){
    var companies = document.getElementById('companies').value.split('\n');
    for(var i=0; i<companies.length; i++){
        thecompany = companies[i].trim();
        thesearchurl = 'https://www.linkedin.com/vsearch/c?type=companies&keywords=' + thecompany;
        chrome.extension.create({url: thesearchurl, selected:false})
    }
}

1 个答案:

答案 0 :(得分:2)

你现在有2个小错误。首先,您应该使用script-tag而不是style来包含javascript文件。第二:最好在页面准备好后加载javascript。要修复这些,请按照以下步骤进行操作

  1. 删除行ToString
  2. 将此FromString添加到<style type="text/javascript" src="popup.js"></style>之前的一行。