IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions.

Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8.

The code I am using is based on the following example:

// Setting up the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Using XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // Implementing XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper function to extract the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Executing the CORS request.
function makeCorsRequest() {
  // All properties of HTML5 Rocks support CORS.
  var url = 'http://updates.html5rocks.com';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS is not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Oops, an error occurred while processing the request.');
  };

  xhr.send();
}

sourced from http://www.html5rocks.com/en/tutorials/cors/

This should function properly in IE8 with XDomainRequest. When I test the sample on the html5rocks page by clicking "Run sample", it works fine in IE8. However, when I use the same code on my own page, I encounter the "Access is denied" error at the xhr.open() line within XDomainRequest.

This issue has me puzzled - the server configuration is correct, so it must be something related to the frontend. Any help would be greatly appreciated. Thank you!

Answer №1

After encountering some issues with IE8 & 9, I found a helpful article that provided solutions: . The key was implementing blank handler functions and utilizing a 0 timeout for the .send() method.

Below is the modified code that now functions correctly across ie8/9/10/11 & FF/Chrome:

function initiateRequest(url) {

    // Create the XHR object.
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open('get', url, true);
    }else if(typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open('get', url);
    }else{
        // CORS not supported.
        xhr = null;
    };

    if (!xhr) {
        return;
    };

    // Response handlers.
    xhr.onload = function() {
        // Deal with the response accordingly. Use xhr.responseText for ie8 compatibility as it lacks .responseXML support
        if(xhr.responseXML) {
            xml = this.responseXML;
        }else if(xhr.responseText){
            xml = new ActiveXObject('Microsoft.XMLDOM');
            xml.loadXML(xhr.responseText);
        };
    };

    xhr.onerror = function() {
        // Handle errors here
    };

    // Set empty handlers as per recommendation to address IE9 issue http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
    xhr.onprogress = function () { };
    xhr.ontimeout = function () { };

    // Invoke send within a timeout to workaround IE9 problem
    setTimeout(function () {
                xhr.send();
            }, 0);

};

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

During post-processing, the elimination of lens flares can sometimes lead to an error known as "copyTexImage2D: framebuffer is

After looking at the lens flares example here: , I'm encountering an issue with post-processing this particular scene. The blocks display correctly, but the light sources and lens flares are missing. Additionally, I am receiving several warnings in t ...

Can someone provide a list of events for the .on function in Vanilla NodeJS?

Currently experimenting with NodeJS by testing basic backend functionalities like sending various HTTP requests from my index.html file to the server.js file. I plan to delve into Express soon. I've noticed a lack of documentation on NodeJS 'eve ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

I have noticed an issue when it comes to transmitting and receiving parameters

Is there a way to incorporate an XML translation into an HTML dropdown list using AJAX? I have been trying to send the parameter using the GET method, but the JSP file responsible for generating the XML is not receiving it. var url = "responsexml.jsp"; ur ...

Updating HTML content based on an active user session using Node.js/Express - A Step-by-Step Guide

I'm struggling to find a way to remove the login/signup buttons once a user has successfully logged in. The issue lies within my header file that needs some modification. <section class="header"> <div class="wrapper"> <nav ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Attempting to utilize React Router V5 to display various layout designs

I have a React application with two different layouts: the "main layout" and the "auth layout". I have noticed that while the main layout pages function correctly, the auth layout pages do not seem to load. When attempting to access "/login", I am directed ...

Retrieve the most recent version of the document stored in MongoDB

Is there a way to retrieve the _id (the Mongo ObjectID) of an updated document without having to find it by newData/oldData? I attempted the following: ... collection.update(oldData, newData, function(err, doc) { console.log(docs); // This prints "1" ...

I'm completely stuck trying to figure out how to implement validation on an MVC Ajax modal box

Utilizing JQM to create AJAX modal boxes has been quite a challenge for me. On a regular page, there is a link that triggers the Ajax modal box. Fortunately, the Ajax modal launches successfully and contains just a textbox and a button. The issue arises ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

Fetching PHP file in WordPress with ajax

Is it possible to use AJAX to request PHP files like "single.php" or "page.php" in WordPress instead of using functions? Thank you. ...

What is the best way to retrieve the reference value from a dropdown box and pass it to another component?

Currently, I am in the process of creating a chat application using socket.io. Within this application, there is a dashboard component that consists of two child components known as Room.js and Chat.js. The Room component serves the purpose of selecting th ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

Unable to apply ng-class when condition is met after ng-click

I am currently experiencing an issue with ng-class. When I click, I pass a variable and then check if it is true in ng-class. If it is indeed true, I append the "col-xs-6" class. Here is what I have attempted: <div ng-class="{'col-xs-6': myV ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

"An error was encountered with the JSON acceptance due to an

When I call an external json API, the response is coming back as JSON. If I don't specify the datatype as JSONP, the API fails due to an access control issue. I can successfully hit the API with Postman and receive the response. However, in the conso ...

Tips on toggling the visibility of div elements with JavaScript

In my selection block, I have three categories of elements and associated Divs. The goal is to display the related divs when a category is selected, while keeping them hidden otherwise. Specifically, I want the husband_name and number_pregnancy divs to be ...

The lack of functionality for lockOrientation in Cordova is causing issues

Currently working with Cordova, I am attempting to set the screen orientation to landscape for Android. Utilizing the screen-orientation plugin found at: https://www.npmjs.com/package/cordova-plugin-screen-orientation In my JavaScript code, I have impleme ...