The Ajax request was denied because the Origin was set to 'null', even though the origin is the same and not localhost or a local file

Unresolved Mystery

I have encountered an issue with how Chrome (version 47.0.2526.73) handles xml files. Despite working perfectly in Firefox (version 43.0.4), the code fails to function as expected in Chrome. As a result, I am left wondering why this discrepancy exists and how I can resolve it for Chrome.

The Goal:

My objective is to create a JavaScript bookmarklet that can check sitemap xml links for various HTTP error statuses such as 404s or 500s.

The Problematic Code Snippet:

    var siteMap="http://www.example.com/sitemap.xml";
    var httpPoke = function(url,callback){
        var x;
        x = new XMLHttpRequest();
        x.open('HEAD', url);
        x.onreadystatechange = function() {
            if (this.readyState == this.DONE) {
                callback(this.status);
            }
        }
        x.send();
    };  

    var response=httpPoke(siteMap,function(n){
                console.log(n);
                });

When executing this code on any page within the domain, the response is:

    200

However, upon navigating to the actual sitemap at http://www.example.com/sitemap.xml, the same code produces the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

This poses a challenge to my plan of providing a bookmarklet that can be used directly on the sitemap itself.

How to Reproduce the Issue:

1) Locate an XML file from a website by searching "filetype:xml sitemap" and choose one that leads to a direct XML file.

2) Implement the provided code snippet either as a bookmarklet or in your browser's developer console.

3) Ensure that the variable siteMap is set to the current URL to comply with CORS. You may even use siteMap=location.href;

You will observe that while this setup works in Firefox, it encounters issues in Chrome.

Note:

Executing code FROM an HTML page, targeting an HTML page does work.
Executing code FROM an HTML page, targeting an XML page does work.
Executing code FROM an XML page, targeting an HTML page does not work.
Executing code FROM an XML page, targeting an XML page does not work.

Steps Taken So Far:

In researching this issue, most resources focus on:

  1. Cross domain requests
  2. Having the source or target on localhost, file:///, or other local servers.

My situation does not fall under either of these categories.

Answer №1

Alright.

Prior to this, I stated:

When you open an XML file using Firefox or Chrome (or even IE), what you see is actually a document generated by the browser's built-in XML parser.

In Chrome's case, it originates from (nodomain) and is identified as follows:

/* Copyright 2014 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

Despite the URL appearing as "http://www.example.com/sitemap.xml", and when checking the console window.location.href shows "http://www.example.com/sitemap.xml", and location.origin as ""http://www.example.com", the actual origin is (nodomain) similar to an extension page because it essentially is one.

Therefore, the origin for XML pages is always null.

This may not necessarily hold true.

I came across this:
Chrome adding Origin header to same-origin request

Tests on Firefox reveal that FF does not set Origin for same-origin GET or HEAD requests, unlike Chrome which does. While this usually isn't problematic, on XML pages document.domain is null. Hence, the origin it sets turns out to be null.

Could this be a bug in Chrome? Or perhaps intentional?

I'm still not entirely satisfied with my explanation...

Give this a try:

  • Visit any XML page in Chrome.
  • In the console, initiate an AJAX request.
  • Examine the request headers in the network tab:

    Accept:*/*
     Accept-Encoding:gzip, deflate, sdch
     Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
     Cache-Control:no-cache
     Connection:keep-alive
     Host:www.example.com
     Origin:null
     Pragma:no-cache
     User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36

Let's give jaromanda-x some kudos for sparking the intuition that led me to these discoveries.

Answer №2

Is your

http://www.sample.com/sitemap.xml
located on a different domain than where your script is running? If so, the browser may block the request for security reasons. Consider learning about how to implement CORS

Typical web pages can utilize the XMLHttpRequest object for data exchange with remote servers, but are constrained by the same origin policy. However, extensions have more freedom in this regard. With appropriate permissions, an extension can communicate with remote servers beyond its own origin.

To delve deeper into the nuances of the same origin policy, check out the information available here

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

Working with HTML5 Canvas to Clip Images

Is there a way to implement a tileset image in canvas like this one? I am trying to figure out how to make it so that clicking on the first tile returns 0, clicking on the tenth tile returns 9, and so on... Any suggestions on how to clip a tileset on an ...

creating a powerful ajax search feature for mysql databases

Currently, I am developing a search engine for a small database, but I believe that my approach to constructing it has been somewhat bloated. Does anyone have any suggestions on how to streamline the AJAX code? Here is a snippet of my ajax.php file... < ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Using a setInterval loop in Javascript to play an audio clip can lead to off-beat rhythms and occasional dropouts, especially

I attempted to play a very small and short mp3 file (5kb, 200ms) using JavaScript and looping it with setInterval. It functions smoothly on desktop browsers without any issues. However, when I try to play the same file on a mid-range android phone (both b ...

Running a JavaScript file enclosed within an AJAX response

I have a web application built with HTML5 that utilizes jquery 3.2.1. Within the application, there is a search feature that makes an ajax request. The response from this request includes HTML code, which contains a <script> tag linking to a js file ...

Revisiting unions with TypeGraphQL

Here is the code snippet I'm working with: const retrieveUsers = ({ Model, options, }) => Model.find(options).catch((e) => { throw e; }); @ObjectType({ description: "User model" }) @Entity() export class UserModel extends BaseEnti ...

Incorporating an image prior to the "contains" term with the help of JavaScript

Seeking assistance with the code snippet below without altering the text targeted in my "a:contains" statement. The challenge lies in determining the appropriate placement of ::before in the script provided. Link: https://jsfiddle.net/onw7aqem/ ...

Implement a redux-form within a react-bootstrap modal

I am facing a challenge with incorporating a multipage 'redux-form' form into a react-bootstrap modal. My goal is to have the form displayed within the modal overlay when the modal is opened. How can this be achieved? The code below is producin ...

Error encountered when trying to add headers property in fetch during React development, triggering CORS restriction

The error message below is from the Network section of Firefox: https://i.sstatic.net/tIx6Q.png I attempted to resolve the aforementioned error by including a headers property within the standard fetch function when making a React API request (or any ES6 ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

The error message "Seed is not defined" is raised when the program attempts to

I'm currently diving into fullstack vue and I'm perplexed by the error occurring in this particular scenario. window.Seed = (function () { const submissions = [ { id: 1, title: 'Yellow Pail', ...

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

What is the method for retrieving the active element with Waypoint?

Currently, I am implementing Waypoint (version 7.3.2) in my React project using React version 16. My goal is to create a scrollable list of items where each item fades out as it reaches the top of the container div. My main inquiry is how can I obtain a re ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

Guide on making a Key Object in Node.js

I've been struggling for the past few days to decode RSA base64 strings in a Node.js environment. Unfortunately, many of the available modules lack proper documentation, or I might be overlooking something crucial. The issue arises from the fact that ...

Tips for incorporating filtering and sorting functionality in a API-focused application using React and Next.js

In my current project, I am developing a React application using Next.js. The main goal is to fetch data from an API and display cards based on user-selected filters. Specifically, I aim to retrieve the cards initially and then filter them according to the ...

Is it possible to interact with a realm instance generated by a JavaScript code using a Java native module through the React Native bridge?

Utilizing Realm in my react-native application via the JavaScript API has been great for persisting user data. However, I now find myself needing to access this Realm instance from a native module (specifically the react-native bridge in Android) in order ...

Enter the text value into the input field using live search through AJAX

I stumbled upon this AJAX Live Search PHP script that functions perfectly. Here is the Live Preview. However, instead of opening a new window when clicked, I want the text of the clicked element to be placed in the search box. After modifying the search.ph ...