我是 HTML 和 JS 新手。我正在尝试使用 Chrome 扩展程序将按钮注入(inject)现有页面。我想在单击按钮时提交搜索表单,但目前它在页面加载时提交表单,然后重复提交。我做错了什么?
这是我的 list .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';
最佳答案
您需要将处理程序包装到函数中:
document.getElementById("nav-section").appendChild(button).onclick=function() { window.location.href='https://test/search?....c' };
因为当前您的代码执行方式为:
- 执行
window.location.href='https://test/search?....c';
这会立即重新加载您的页面。 - 将此执行结果分配给
onclick
处理程序。当您的页面重新加载时,这不会产生任何影响。
关于javascript - Onclick 按钮在页面加载时自动运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357500/