我想创建一个Google Chrome扩展程序,以便将数据从弹出窗体发送到localhost服务器。我创建了以下文件。一切正常但数据不会发送到localhost服务器。 有谁可以请帮助我,我的错误在哪里? 感谢。
的manifest.json
{
"manifest_version": 2,
"name": "server Plug-ins",
"description": "Send data to database",
"version": "1.0",
"icons": {
"48": "icon.png"
},
"permissions": [
"history",
"browsingData",
"tabs",
"<all_urls>",
"http://192.168.1.222/*",
"storage"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Send data to server!"
}
}
alert.js
document.write(" i am here . . .");
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://192.168.1.222/my_parse_file.php";
var fn = document.getElementById("name").value;
var ln = document.getElementById("details").value;
var vars = "name="+fn+"&details="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
popup.html
<body>
<label for="">Name</label><br><input type="text" id="name"> <br>
<label for="">Details</label><textarea id="details"></textarea>
<input id="clickme" name="myBtn" type="submit" value="click me">
<script type="text/javascript" src="popup.js"></script>
</body>
popup.js
function hello() {
chrome.tabs.executeScript({
file: 'alert.js'
});
}
document.getElementById('clickme').addEventListener('click', hello);
答案 0 :(得分:-1)
我认为问题是如果input
脚本正在运行,则无法在上下文中访问您的弹出式alert.js
元素。
在alert.js
的上下文中,document
指的是您在其中注入脚本的标签文档。
您可以执行以下操作以使其正常工作,并使用以下内容替换popup.js文件的内容:
function hello() {
function contentScript(fn, ln){
document.write(" i am here . . .");
var hr = new XMLHttpRequest();
var url = "http://192.168.1.222/my_parse_file.php";
var vars = "name="+fn+"&details="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
}
var fn = document.getElementById("name").value;
var ln = document.getElementById("details").value;
chrome.tabs.executeScript({
code: (contentScript.toString() + "\ncontentScript('" + fn + "', '" + ln + "');")
});
}
document.getElementById('clickme').addEventListener('click', hello);
您可以删除alert.js
文件,因为现在,扩展程序会直接注入JavaScript代码而不是注入文件。