Why are my ajax calls synchronous in Chrome extension?

402 views Asked by At

I've been trying to use some ajax in a chrome extension.

I have a content script which is supposed to add some html to an existing page.

I've tried JQuery.get, JQuery.load and ng-include.

And all of them show a warning in the console, telling me synchronous XHR are deprecated (aren't these assynchronous by nature???). And then the page shows this weird behavior, tells me that some Pusher is not defined, then refreshes the page and kills my inserted div.

What could be wrong??

Sample code - If I enable the first var txt, it works perfectly. If instead I enable the second var txt (commented), it fails.

 //this first line works perfectly
 var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}</div>'; 

//this shows the warning and a really weird behavior
//var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}<div ng-include="' + "'myhtml.html'" + '"></div></div>'; 


$('#a-certain-div-in-the-page').after(txt)

var app = angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.testing = 'Welcome!';
    });

angular.bootstrap(document, ['myApp']);
1

There are 1 answers

0
Daniel Möller On BEST ANSWER

Ok, here is what happens:

1 - The extension domain is different from the page domain, so it tried to load things from the page's domain, not from the extension files. (And the resource was not found). The warning message is totally misleading in this case.

Solution: use chrome.extention.getURL('myhtml.html') to get the proper complete url. Or concatenate strings using your extension's ID to create a full path.

 var txt = '<div id="myNewDiv" ng-controller="myController">{{testing}}<div ng-include="' + "'" + chrome.extension.getURL('myhtml.html') + "'" + '"></div></div>'; 

2 - Even doing that, there is also a cross-domain request issue. The page only accepts requests from its own domain, unless you give it the right permissions. It's necessary to add in the manifest.json file the permission to this resource:

{
    "manifest_version": 2,

    ..... among many others ....

    "web_accessible_resources": [
        "myhtml.html"
    ]

}