问题
I have a very simple Chrome App. It displays a popup with a search box. Submitting the search box opens my site in a new tab.
The search box is empty by default. When it is empty, clicking submit shouldn't do anything. My popup.html looks like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>foo</title>
<link rel="stylesheet" type="text/css" href="popup.css" />
</head>
<body>
<div id="srch">
<form target="_blank" action="foo.php" method="get" onsubmit="if (document.getElementById('box').value.length < 1) return false;">
<input type="text" id="box" name="foo" value="" />
<input type="submit" value="foo" />
</form>
</div>
</body>
</html>
If I open popup.html in a browser, then clicking submit does nothing. But if I open it as the Chrome App, then clicking submit still submits the form, without anything in it. So it seems that the JavaScript is being ignored.
回答1:
Problem in your Script
Chrome Extensions do not allow inline JS or <script>
tag in HTML Code, so your code onsubmit="if
will not surpass CSP, after Eliminating these i got your script running.
Sample Demonstration of your code
manifest.json
Registered Browser action to manifest file.
{
"name": "chrome-app-onsubmit",
"description": "http://stackoverflow.com/questions/14263946/chrome-app-onsubmit",
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_popup": "popup.html"
}
}
popup.html
Eliminated Inline Script
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>foo</title>
<script src="popup.js"></script>
</head>
<body>
<div id="srch">
<input type="text" id="box" name="foo" value="" />
<input type ="submit" id="submit" value="foo" />
</div>
</body>
</html>
popup.js
Your functionality goes here.
function _clickHandler() {
if (document.getElementById('box').value.length < 1) {
return false;
} else {
console.log("In Success Handler..");
//Do Your AJAX Request Call here
}
}
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("submit").onclick = _clickHandler;
});
Check How to Load an Extension for testing your script.
Reference
- Content Security Policy
回答2:
try this...different browsers can be picky about javascript formatting...just a thought
onsubmit="if (document.getElementById('box').value.length < 1) {return false;};">
来源:https://stackoverflow.com/questions/14263946/chrome-app-onsubmit