Using JavaScript to make an AJAX call to a different domain while bypassing the Content Security Policy restrictions

While parsing a web page, I need to initiate an AJAX call to my localhost depending on the content. The purpose is to exchange data using a PHP script on my localhost, possibly in JSON format (still under testing).

This process is part of a plugin that I am currently testing on Google's page.

I am following a simple AJAX example from:

https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp

I have successfully managed to make the AJAX call itself.

//loadDoc("http://localhost/index.php", myCallback);  <-- this NOT
//loadDoc("https://www.google.de", myCallback);   <-- this WORKS

/*
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified  (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified  (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
*/

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
 };
  xhttp.open("GET", url, true);
  xhttp.send();
}


function myCallback(xhttp) {

  alert("I'm alive from my local server");

}

The main issue I encountered is that the "Content Security Policy" does not permit cross-domain calls even within my own context (my browser, FF 53).

It seems that this restriction can be bypassed for GET requests by injecting a script into the DOM, as demonstrated in this article:

AJAX cross domain call

and especially with the insights shared by Rob W in this post:

Insert code into the page context using a content script

Despite trying out this approach, I still encounter issues.

// var actualCode = ['/* Code here. Example: */' + 'alert(0);',
                  // '// Beware! This array have to be joined',
                  // '// using a newline. Otherwise, missing semicolons',
                  // '// or single-line comments (//) will mess up your',
                  // '// code ----->'].join('\n');

var script = document.createElement('script');
script.src = "http://localhost/index.php";
script.type = "text/javascript";
document.appendChild(script);
// script.textContent = actualCode;
// (document.head||document.documentElement).appendChild(script);
// script.remove();

Since I am only using my localhost, security concerns are not a priority. Can anyone point out what I might be missing here?

EDITED

The errors displayed by Firefox debugger are highlighted below:

Blocked loading mixed active content “http://localhost/index.php”[Learn More]  axtest.js:16
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified  (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified  (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified

Answer №1

Make sure to add it either to the body or head section, not directly to the root document:

document.head.appendChild(script);

The error about mixed active content occurs when you load the initial page using https (SSL) and then try to load a http (unsecured) URL. To resolve this, either load the page without https or configure https on the URL you are requesting.

Answer №2

After already selecting an answer, I came across a much simpler solution that perfectly suits my needs. The key lies in adjusting the local browser security policy, with no requirement for injecting any JS code.

Initially, it was necessary to update the plugin's manifest.json file with the following:

    "permissions": [
      "history",
      "browsingData",
        "tabs",
        "<all_urls>",
        "http://localhost/*",
        "storage"
  ]

Secondly (credit to @Quentin), the local browser policy should be reconfigured. To disable CSP for the entire browser, simply turn off security.csp.enable in the about:config menu

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

Error message displayed: "Unexpected token 'H' when attempting to render Markdown

I've been working with the react markdown library and wanted to share my code: import Markdown from 'react-markdown'; import PreClass from './PreClass'; type MarkdownFormatTextProps = { markdown: string; tagName?: string; ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...

How to Calculate the Time Interval Between Two CORS Requests Using jQuery AJAX

When using jQuery's $.ajax to make a CORS request to a web service, there is typically a pre-flight request followed by the actual POST request. I have observed that when there is a time gap between making two web service calls, both a pre-flight and ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

Issue: Unable to access API target map in AGM using Google Map API

I attempted to integrate a Google map with multiple locations. While I was successful in using an Iframe for one location, I struggled to implement multiple locations within the Iframe. As a result, I tried utilizing AGM and used the same APIKey that I ha ...

Having trouble getting the AJAX script to change the background in Internet Explorer?

I'm currently experiencing an issue with an ajax script. Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#savecolor').click(function(){ var myVar = 'data= ...

Tips for securely implementing JSON web tokens when integrating an external application with the WordPress REST API

I have a query regarding JWT. Let's consider this situation. A -> wordpress site with wp rest api enabled; B -> External application (for example, a simple javascript/jQuery app) Suppose I want to make a post request or create a new post on t ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Canvas ctx.drawImage() function not functioning properly

I've encountered an issue while trying to display images in a canvas using my rendering function. Here is the code snippet: function populateSquareImages(){ for(var i = 0, ii = squares.length; i < ii; i++) { if(squares[i].hasImage) { ...

Wookmark js isn't designed to generate columns from scratch

I am attempting to utilize the Wookmark jQuery plugin in order to create a layout similar to Pinterest. However, I am encountering an issue where Wookmark is not creating columns within the li elements, instead it is simply stacking images on top of each o ...

how to name a collection variable in MongoDB shell using JavaScript

When using the mongo shell with JavaScript, is it possible to dynamically set the collection name in order to work with multiple collections? db.collection.insert() ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue. Take a look at the screenshot and code snippet provided: function myF ...

What is the best way to switch from rows to cards in Bootstrap version 5.3?

In my current project, Next JS is the framework I am working with. I am faced with the challenge of creating a card layout that adapts based on device size - for smaller devices, I want a plain card with the image on top and text below, similar to Bootstra ...