问题
I'm trying to build my first Chrome Extension. I need it to have a simple form that submits. I'm having trouble getting anything to run on my popup.js file. I found this post to be similar but can't seem to get even the basic logging to work in the console. How to get value of form submission popup.html chrome extension
Here is my popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
<form id="useCasePostForm">
<input type="text" id="useCase" />
<input type="submit">
</form>
</body>
</html>
Here is my current try at the popup.js
$(function() {
console.log("console logging works");
document.getElementById("useCasePostForm").addEventListener("submit", handleClick, false);
function handleClick(val) {
console.log("calling handleClick"); //printing
console.log(val); //prints undefined
chrome.runtime.sendMessage({
from: "popup",
subject: val
});
}
});
My other attempt I came up with this which I think I was getting a bit ahead of myself on:
window.addEventListener('load', function(evt) {
// Handle the bookmark form submit event with our useCasePost function
document.getElementById('useCasePostForm')
.addEventListener('submit', useCasePostFunc);
});
function useCasePostFunc(event){
event.preventDefault();
conosle.log("in the function")
var useCase = document.getElementById("useCase")
//The URL to POST our data to
var postUrl = 'https://localhost:8080/useCases/create';
console.log("in function")
// Set up an asynchronous AJAX POST request
$.ajax({
'url': postUrl,
"type": "POST",
data:{
id:4
}
})
}
Here is my manifest file as well.
{
"manifest_version": 2,
"name": "PIT",
"version": "0.1",
"background": {
"scripts":["background.js"]
},
"browser_action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"https://app.hubspot.com/*"
],
"js": ["jquery-3.4.1.min.js", "content.js"]
}
],
"permissions": [
"webRequest",
"tabs",
"<all_urls>"
]
}
If anyone has any pointers on how I can receive the form submission as a first step it would be greatly appreciated.
回答1:
To follow up on this, this ended up being the winning code.
document.addEventListener('DOMContentLoaded', function () {
console.log("the doc loaded")
var form = document.getElementById("useCasePostForm")
console.log(form)
form.addEventListener('submit',function(e){
e.preventDefault()
console.log("added to the form")
})
});
来源:https://stackoverflow.com/questions/57260281/form-submission-within-a-chrome-extension-popup