There are several questions that handle passing of data from a content script to a background script:
How to pass an array from background.js to inject.js (content) script (Chrome Extension)
sendMessage from extension background or popup to content script doesn't work
but, to my knowledge, there are no answers on form handlers. As an example:
manifest.json:
{
"manifest_version": 2,
"name": "chrome-extension-bar",
"description": "Chrome Extension Bar",
"version": "1.0",
"browser_action": {
"default_title": "Chrome Extension Bar",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"<all_urls>",
"tabs"
],
"content_security_policy": "script-src 'self' https://ajax.googleapis.com/ https://maxcdn.bootstrapcdn.com ; object-src 'self'"
}
popup.html:
<html>
<head>
<script type="application/javascript" charset="utf-8" src="popup.js"></script>
</head>
<body class="body-popup">
// nothing needed here
</body>
</html>
popup.js:
chrome.tabs.executeScript({
file: "add-extension-content-script.js"
}, function() {
console.log("Added extension!");
})
add-extension-content-script.js:
var form_element = htmlToElement(
`
<div>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<button id="idSendButton" type="button" class="btn btn-secondary">Send</button>
</form>
`
);
var current_title_bar = document.getElementById("global-nav");
current_title_bar.appendChild(form_element);
document.getElementById("idSendButton").addEventListener('click', function () {
chrome.runtime.sendMessage({"name" : document.getElementById("fname").value}, function(response) {
console.log('Got response: ' + response.farewell);
});
});
How can I make the form send messages to the content script? The content script clicks buttons on the page upon receiving form input.