Search code examples
javascriptajaxcordovabackbone.jsphonegap

Override Backbone.ajax method to use cordovaHTTP


I am working on a phonegap app which uses Backbone JS. During ajax calls the header contains:

"Origin":"file://"

Which is not supported by the server. I tried to set Origin header as null but in chrome it is not allowed.

Backbone.ajax = function() {  
    arguments[0].headers = {
        'Accept': "application/json",
        'Origin': "null"
    };
    return Backbone.$.ajax.apply(Backbone.$, arguments);      
  };

Which throws error:

Refused to set unsafe header "Origin"

Only work around I can think of to solve this issue is to use the cordovaHttp plugin. But I am unable to figure out how to override Backbone.ajax to use cordovHTTP.

Link to the cordova plugin: https://github.com/silkimen/cordova-plugin-advanced-http

Although this is related to CORS, my question is specific to Overriding Backbone ajax method using the cordovaHttpPlugin


Solution

  • It works:

    function isPhoneGap() {
        return (window.cordova || window.PhoneGap || window.phonegap) 
        && /^file:\/{3}[^\/]/i.test(window.location.href) 
        && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
    }
    
    Backbone.sync = function( method, model, options ) {
    
            if(method == "read"){
    
                if(isPhoneGap()){
                    cordova.plugin.http.get(model.url, {}, { Origin: "null" }, function(response) {
                        // prints 200
                        console.log(response.status);
                        try {
                            options.success(JSON.parse(response.data));
                        } catch(e) {
                            console.error("JSON parsing error");
                        }
                    }, function(response) {
                        console.log(response.status);
                        console.log(response.error);
                    });
                }else{
    
                    $.ajax({
                        type : 'GET',
                        url : model.url,
                        dataType : 'json',
                        success : function(data) {
                            console.log(data);
                            if(model instanceof Backbone.Collection){
                                model.reset(JSON.parse(JSON.stringify(data)));
                            }else{
                                model.set(JSON.parse(JSON.stringify(data)));
                            }
                        }
                    });
                }
            }
      }