【发布时间】:2014-02-09 03:04:25
【问题描述】:
第一次使用该网站提出问题。我是 Chrome 扩展程序的新手,所以我确定我犯了一些愚蠢的错误。我提前道歉。
我正在尝试获取当前选项卡的 url 并将其发布到一个 URL,然后该 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
}
});
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
}
}
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);
});
});
});
});
非常感谢您提供任何人可以分享的任何光。
【问题讨论】:
-
这里为什么使用
background.js?为什么不把main.js的内容直接放到background.js中 -
我想没有帮助,但我尝试了你原来的
XMLHttpRequestsn-p,简化为始终 POST 到特定的 URI,它对我来说很好用。谢谢你的例子!
标签: javascript post google-chrome-extension xmlhttprequest