我一直在使用NodeJS和RESTful API练习,几天后我决定尝试使用Chrome扩展程序。
我有一个表单(Chrome扩展程序),我想通过REST API使用HTTP POST将数据发送到我的服务器。
我已经关注了tutorial
问题是以下代码没有做任何事情。 我不知道为什么。我已按照上面的教程,但没有任何反应......没有console.log,没有......
任何人都可以帮助我吗?
这是我的代码:
popup.js
function postLink() {
event.preventDefault();
var postUrl = 'http://url.com:port';
var statusDisplay = null;
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
var torrentUrl = encodeURIComponent(document.getElementById('link').value),
params = "url=" + torrentUrl;
console.log("torrentUrl -> " + torrentUrl);
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
console.log("params -> " + params);
xhr.send(params);
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Downloading!';
console.log("Everything is alright!");
//window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error: ' + xhr.statusText;
console.log("Ooouch! U.u");
}
}
};
// Send the request and set status
//xhr.send(params);
statusDisplay.innerHTML = 'Preparing...';
}
document.addEventListener('load', function(evt) {
statusDisplay = document.getElementById('status-display');
document.getElementById('postForm').addEventListener('submit', postLink);
});
popup.html
<!doctype html>
<html>
<head>
<title>Link</title>
<script src="popup.js"></script>
</head>
<body>
<div>
<form id="postForm">
<input type="text" id="link" name="link" placeholder="link" size=40><br>
<input type="submit" value="Submit">
<span id="status-display"></span>
</form>
</div>
</body>
</html>
的manifest.json
{
"manifest_version": 2,
"name": "LinkExtension",
"description": "BlaBlaBla",
"version": "0.1",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}