简体   繁体   中英

Form Submission within a Chrome Extension popup

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.

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")
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM