简体   繁体   中英

CSP issue using AJAX requests on in a Crossrider extension

I'm trying to run an AJAX request in a Crossrider extension but I get a CSP related error.

Here's my code (modified for privacy):

$.ajax({
  url : "https://example.com/...",
  type : 'POST',
  dataType : 'json',
  data : {user: "user", pass: "pass"}
  }).done(function(data) {
    console.log("POST Succeeded");
  }).fail(function(a, b, c, d) {
    console.log("POST Failed");
});

If I run the code from the extension it doesn't work and it gives an "Access Denied" error!

Why cannot I run the request in my Crossrider extension?

Using standard jQuery AJAX methods in an extension can often lead to cross domain issues that prevent access to the content; hence, when coding Crossrider extensions it's best practice to use the appAPI.request methods provided with the framework that are developed specifically to be cross browser and cross domain safe.

So in your case, you could rewrite the POST request in your extension.js or background.js , as follows:

appAPI.ready(function($) {
  appAPI.request.post({
    url: "https://example.com/...",
    contentType: "application/json",
    postData: {user: "user", pass: "pass"},
    onSuccess: function(response) {
      console.log("POST Succeeded");
    },
    onFailure: function(code) {
      console.log("POST Failed");
    }
  });
});

[ Disclosure : I am a Crossrider employee]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM