dil*_*ger 3 javascript post xmlhttprequest google-chrome-extension
第一次使用网站提问.我是Chrome扩展程序的新用户,所以我确定我犯了一些愚蠢的错误.我提前道歉.
我正在尝试获取当前选项卡的URL并将其POST到URL,然后将其接收并将其推送到数据库中.就像我自己的个人书签服务.我已经尽可能多地进行了调试,数据正在一直到我发送XHR请求的地方..但是当我在服务器端脚本上回显它时,数据不会出现.我确认它正在击中我的URL因为我是控制台记录输出...但是再次没有传递数据.
BACKGROUND.JS
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.open(method, request.url, true);
xhttp.send(request.data);
xhttp.onload = function() {
callback(xhttp.responseText);
};
return true
}
});
Run Code Online (Sandbox Code Playgroud)
的manifest.json
{
"name": "bookmarker",
"version": "0.0.1",
"manifest_version": 2,
"description": "POSTIN BOOKMARKS!",
"homepage_url": "URL",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": [
"contentSettings",
"cookies",
"tabs",
"geolocation",
"http://*/*"
],
"content_scripts": [
{
"js": ["contentscript.js"],
"matches": ["http://*/*"]
}
],
"browser_action": {
"default_icon": "icons/icon16.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
Run Code Online (Sandbox Code Playgroud)
MAIN.JS
jQuery(function() {
jQuery('.reminded').on('click', function(e){
e.preventDefault();
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var url = tabs[0].url,
date = 1391048414,
clientId = 1234
chrome.runtime.sendMessage({
method: "POST",
action: "xhttp",
url: "http://www.API.com/endpoint",
data: {url: url, date: date, clientId: clientId}
}, function(responseText) {
console.log(responseText);
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
非常感谢您提前与任何人分享的光.
你没有提到其中使用"main.js",但我想它在弹出的页面中使用的,对不对?当您在清单文件中声明权限时,弹出页面还可以在Chrome扩展程序中发出跨域请求.因此,只需jQuery.ajax直接使用跨域请求:
jQuery.ajax({
type: "POST",
url: "http://www.API.com/endpoint",
data: {url: url, date: date, clientId: clientId},
success: function(data) {
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)
因为,在你的问题的代码失败,因为你要提交一个JavaScript对象(备案{url: url, date: date, clientId: clientId}通过.send的方法XMLHttpRequest,这是没有意义的,你的服务器会接收字符串[object Object],因为对象的默认序列化.
要获得你的原始代码工作,你应该jQuery.param用来序列化表单数据和xhttp.setRequestHeader("Content-Type", "application/x-www-form-url-encoded");.
| 归档时间: |
|
| 查看次数: |
6691 次 |
| 最近记录: |