Chrome扩展帖子请求不发送数据

时间:2014-01-20 03:05:12

标签: javascript post google-chrome-extension xmlhttprequest

首次使用该网站提问。我是Chrome扩展程序的新用户,所以我确定我犯了一些愚蠢的错误。我提前道歉。

我正在尝试抓取当前标签的网址并将其发布到一个网址,然后将其接收并将其推送到数据库中。就像我自己的个人书签服务。我已经尽可能多地进行了调试,数据正在一直到我发送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);
            });
        });
    });
});

非常感谢您提前与任何人分享的任何光明。

1 个答案:

答案 0 :(得分:6)

你没有提到使用“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);
    }
});

对于记录,您的问题中的代码失败了,因为您尝试通过{url: url, date: date, clientId: clientId}的{​​{1}}方法提交JavaScript对象.send。这没有任何意义,由于对象的默认序列化,您的服务器将收到字符串XMLHttpRequest 要使原始代码生效,您应使用jQuery.param序列化表单数据和[object Object]