Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for development), the call fails due to Chrome sending an OPTIONS preflight request to the salesforce server, which does not support CORS.

Surprisingly, IE does not send a CORS preflight request, so I expected the call to work without any issues. However, I encountered an "Access is Denied" error deep within the angular code.

Upon further investigation, I found that the specific line in Angular (v1.2.21) causing the issue is:

xhr.open(method, url, true); (line 8544 in version 1.2.21).

After browsing through discussions on GitHub, Google Groups, and Stack Overflow, it seems that the problem lies in how IE handles cross-domain requests and which XHR object is being utilized to make the call.

Previous versions of Angular had addressed this issue by adding a function before the xhr.open() call to fetch the correct XMLHttpRequest object for the IE version in use:

var xhr = createXhr(method);

xhr.open(method, url, true);
forEach(headers, function(value, key) {
  if (isDefined(value)) {
      xhr.setRequestHeader(key, value);
  }
});

Theoretically, this approach should invoke the appropriate xhr object's .open() method. However, I still encounter an "Access is Denied" error at that line.

Suggestions from various sources recommend using XDomainRequest() instead of XMLHttpRequest for cross-domain calls in IE. Despite my skepticism, I manually edited the code in angular.js to utilize XDomainRequest() specifically for our salesforce call:

var xhr;
if (url.indexOf("salesforce.com") > -1) {
  xhr = new XDomainRequest();
}
else {
  xhr = createXhr(method);
}

xhr.open(method, url, true);
forEach(headers, function(value, key) {
  if (isDefined(value)) {
      xhr.setRequestHeader(key, value);
  }
});

However, now the line where xhr.setRequestHeader(key, value) is called fails. Does anyone have insights into what could be causing this issue? It seems unlikely that Angular lacks a solution for handling cross-domain calls in IE, so I must be overlooking something.

Answer №1

Although the issue mentioned is related to IE10, I encountered the same problem with IE8-9 as well. My workaround involved utilizing the cross domain object window.XDomainRequest.

function loadCaptions() {

    //Utilizing XDomainRequest for compatibility with IE8-10, or else angular xhr requests may result in "access denied" error.
    var url = $scope.captionsUrl;
    if (!!window.XDomainRequest) {
        var xdr = new window.XDomainRequest();
        if (xdr) {
            xdr.open("get", url);
            xdr.send();
        }

        return;
    }


//This section is not relevant for stackoverflow users, included only to demonstrate my caption request method leading to "access denied"
    $http.get($scope.captionsUrl)
        .success(function (captionsJson) {
            $scope.captionsList = captionsJson;
            createCaptionsMap();
        })
        .error(function (data, status, headers, config) {
            $cbtErrors.failedToLoadCaptions($scope.captionsUrl);
        });
}

EDIT:

Here's a more comprehensive solution incorporating memory management for a bug in XDR requests and callbacks for "on success"/"on error":

function loadCaptions() {
    //Using XDomainRequest for IE8-9 to prevent "access denied" error from angular get request.
    var url = $scope.captionsUrl;

    if (!!window.XDomainRequest) {
        var xdr = new window.XDomainRequest();

       var removeXDR = function(xdr) {

            var index = global.pendingXDR.indexOf(xdr);
            if (index >= 0) {
                global.pendingXDR.splice(index, 1);
            }
        };

        if (xdr) {
            xdr.onload = function(){
                removeXDR(xdr);
                $scope.captionsList = xdr.responseText;
                createCaptionsMap();
            };
            xdr.onerror = function(){
                removeXDR(xdr);
                $cbtErrors.failedToLoadCaptions($scope.captionsUrl);
            };
            xdr.open("get", url);
            xdr.send();

            global.pendingXDR = [];
            global.pendingXDR.push(xdr);

        }

        return;
    }


//This part can be disregarded by stackoverflow users, just showing how I made caption requests resulting in "access denied"
    $http.get($scope.captionsUrl)
        .success(function (captionsJson) {
            $scope.captionsList = captionsJson;
            createCaptionsMap();
        })
        .error(function (data, status, headers, config) {
            $cbtErrors.failedToLoadCaptions($scope.captionsUrl);
        });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

Move to Fieldset Upon Link Click

Here's an example of what I have implemented so far here It's evident that this is not fully functional due to the PHP and jQuery integration. This demo is just a showcase of my progress. I am looking to create a functionality where clicking on ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...

The jQuery date picker refuses to function correctly when I attempt to initialize it after an AJAX call

I am facing an issue with my jquery-ui datepicker not working within the document.ready function after making an ajax call. However, it works fine when I add it inside the ajax complete function. Can someone please provide assistance on what could be cau ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

Discovering the exact latitude and longitude coordinates along a specific route using Google Maps

I've encountered a problem with finding the latitude and longitude along a given route using Google Maps DirectionsService. I have a JSON dataset containing latitude, longitude, and price details. My goal is to plot markers on the map and determine wh ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

The functionality of Ajax autocomplete with jQuery does not function properly when the text field contains existing text

Currently, I am utilizing Ajax autocomplete for jquery in my project. Below is the HTML code snippet I have implemented: <input type="text" name="autocomplete" id="globalBCCAutoComplete"> Furthermore, here is the JS code utilized for the autocomple ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Ways to adjust image placement and size post-rotation with CSS/JS to ensure it stays within the containing div and avoids being cut off

Check out this jsfiddle I've been experimenting with. The jsfiddle is designed to rotate an image by 90 degrees in either clockwise or anti-clockwise direction upon button click. However, the rotated image currently appears outside of its parent div. ...

Two states each offering a distinct perspective

I am currently working on modularizing my application using angular-ui-router to create a website with two states: main and checkout. In the main state, I want to have multiple "section" tags defined as ui-view items. However, it seems like there is an iss ...

The AngularJS error message states that there is an issue because the $resource function is

I am currently facing an issue with my controller, specifically the error message: TypeError: $resource is not a function This error is pointing to the line var Activities = $resource('/api/activities'); app.controller('AddActivityCtrl& ...

I'm attempting to store the information from fs into a variable, but I'm consistently receiving undefined as the output

I'm currently attempting to save the data that is read by fs into a variable. However, the output I am receiving is undefined. const fs = require("fs"); var storage; fs.readFile("analogData.txt", "utf8", (err, data) =&g ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

I rely on Grunt to manage my Angular 1 app, along with grunt-connect to host the website. However, when I refresh the page, there is no fallback mechanism in place, resulting in a 404 error and

Currently, I am utilizing Grunt to manage my angular 1 application and grunt-connect to serve the website. However, I have encountered an issue where on refresh, there is no fallback mechanism in place which results in a 404 error and a blank white screen. ...

Ways to retrieve several parameters from a controller using Ajax Jquery in Codeigniter

I need to retrieve a list of images from a folder based on a specific ID. Currently, I am able to get the file names but I also require the upload path. Is there a way to obtain both sets of data using a single function? Javascript Code: listFilesOnServ ...

Obtain a file from React Native in order to upload an image, just like using the `<input type="file" onChange={this.fileChangedHandler}>` in web development

After experimenting with different methods, I attempted to achieve the desired result by: var photo = { uri: uriFromCameraRoll, type: 'image/jpeg', name: 'photo.jpg', }; and integrating axios var body = new FormData( ...