Onclick按钮在页面加载时自动运行

时间:2018-03-19 07:10:32

标签: javascript html json google-chrome onclick

我是HTML和JS的新手。我试图通过Chrome扩展程序将按钮注入现有页面。我想在单击按钮时提交搜索表单,但此时它会在页面加载时提交表单,然后重复提交。我做错了什么?

这是我的manifest.json

"browser_action": {
"default_icon": "icon.png",
    "content_scripts" : "script.js"
},

"content_scripts": [
  {
    "matches": ["https://test.com/*"],
    "js": ["script.js"],  
    "run_at": "document_end"
  }

这是我的script.js

var button = document.createElement("button");
var buttonName = document.createTextNode("Search By Tag");
  button.appendChild(buttonName);
    document.getElementById("nav-section").appendChild(button).onclick=window.location.href='https://test/search?....c'; 

2 个答案:

答案 0 :(得分:1)

您需要将处理程序包装到函数中:

document.getElementById("nav-section").appendChild(button).onclick=function() { window.location.href='https://test/search?....c' };

因为目前您的代码执行为:

  1. 执行window.location.href='https://test/search?....c';立即重新加载您的页面。
  2. 将此执行结果分配给onclick处理程序。这对您的网页重新加载没有任何影响。

答案 1 :(得分:1)

您必须在onclick属性中指定一个函数。你可以通过以下方式完成。

var button = document.createElement("button");
var buttonName = document.createTextNode("Search By Tag");
button.appendChild(buttonName);
document.getElementById("nav-section").appendChild(button).onclick = function() {
    window.location.href = 'https://test/search?....c';
}