Chrome: Content scripts experiencing issues with Cross Origin XMLHttpRequest functionality

Within my background script, I am injecting my contentScript using the following method:

chrome.webRequest.onHeadersReceived.addListener(function(details){
    if(isPDF(details))
    {   
        chrome.tabs.executeScript(details.tabId, {file: "content.js", runAt: "document_end"}, function(result){
            if(chrome.runtime.lastError)
            {
                console.log(chrome.runtime.lastError.message);
            }
        });
        return {
            responseHeaders: [{
              name: 'X-Content-Type-Options', 
              value: 'nosniff'
            }, {
              name: 'X-Frame-Options', 
              value: 'deny'
            }]
          };
        }
}, {
    urls: ['*://*/*'],
    types: ['main_frame']
}, ['blocking', 'responseHeaders']);

The content.js file contains the following code snippet:

function reqHandler()
{
    alert("hello");
    var imgData = "" + this.responseText;
    //document.write("" + imgData);
    document.body.innerHTML = "";
    var img = document.createElement("img");
    img.setAttribute("src", 'data:image/jpeg;base64,'  + "" + imgData);
    document.body.appendChild(img);
}

//debugger;
var PDFdata = document.body.innerHTML;  
document.body.innerHTML = "";
var xhr = new XMLHttpRequest();

xhr.onload = reqHandler;
xhr.open("GET", "http://localhost:81/getImage.php", true);
xhr.send(); 

Despite running into an issue while executing a cross-origin XMLHTTPRequest in the above script. My reqHandler function fails to execute after completing the XHR request.

The embedded alert message inside is not visible. What could possibly be causing this problem?

UPDATE Below is the manifest file pertaining to the extension:

{
    "manifest_version": 2,

    "name": "My Extension",
    "version": "1.0",

    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },

    "permissions": [
        "webRequest",
        "<all_urls>",
        "webRequestBlocking",
        "tabs",
        "webNavigation"
    ]
}

Answer №1

As far as I know, only internal extension scripts running in the privileged context, such as the background page script (not content scripts that lack access to privileged APIs), are able to perform Cross-Origin XMLHttpRequests. For more information, refer to the official documentation.

To invoke XHR in your background page script, you can send a message to the tab's content script.

  • In background.js:

    chrome.webRequest.onHeadersReceived.addListener(function(details){
        if(isPDF(details))
        {   
            var xhr = new XMLHttpRequest();
            var tabId = details.tabId; // save id in the local context
            xhr.onload = function() {
                chrome.tabs.sendMessage(tabId, {imgData: this.responseText});
            };
            xhr.open("GET", "http://localhost:81/getImage.php", true);
            xhr.send(); 
            chrome.tabs.executeScript(details.tabId, {file: "content.js", ..............
    ..................
    
  • In content script:

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        if (message.imgData) {
            document.body.innerHTML = "";
            var img = document.createElement("img");
            img.src = "data:image/jpeg;base64," + message.imgData;
            document.body.appendChild(img);
        }
    });
    

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

Exploring the World of Dynamic Table ID Access in Rails 5 with Coffeescript

Within my Index view, I have a table that I want to dynamically populate with an ID. This is what I've attempted so far: id="table_<%= @controller_name %>" The method in my controller looks like this: def get_controller_name @controller_nam ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

What could be the reason for the malfunctioning of the Angular options tracking by ID feature?

I seem to be facing an issue with my code: There is an object that holds the id of an item, along with an array containing these items. I require a 'select' element to display the currently selected item and allow for changing the selection. Th ...

"Exploring the depths of PHP: Generating a JSON string from an array

I am trying to work with PHP code in an Object-Oriented manner and the values I am getting are objects. However, I need to convert these O.O.P objects into JSON data for use by JavaScript. So, I converted my objects into arrays on the PHP end, but when I t ...

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...

Retrieving information from the logger to provide back to the web application

I'm almost there, but not quite. The logger is showing the search results, but I still can't get them to display on the web app. The search function works on the web app and the results show up in the logger. Any advice would be appreciated. Th ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

When XMLHttprequest is used to send a POST request, it sometimes

Here is the code I'm using to send a request: let ajaxHandler = new XMLHttpRequest(); ajaxHandler.onreadystatechange = function() { if(ajaxHandler.readyState == 4) { console.log(ajaxHandler.responseText); } } ajaxHandler.open("POST", ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Angularjs collapsible toggle

I am having trouble launching a simple example of collapse. When I click on the "Toggle collapse" button, nothing happens. There are no errors in the console, but there is one warning in Visual Studio. What could be causing this issue and how can I fix it? ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

How can we trigger a function once the API requests within a for loop have completed?

Within this for loop, a maximum of 'time' iterations are specified. With each iteration, a GET call is made to retrieve data that must be added to the obj object. I am seeking a method to determine when all 3 GETS have been completed along with ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

Stagnant className in map persisting despite changes being made

I am in the process of updating my react className based on changes to the active status within the sites variable, which is iterated over with a map function. The issue I'm facing is that the 'inactive' className persists even when the act ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

Tips for successfully passing the selected dropdown value into contextscope within AngularJS

Hey there! I currently have a dropdown list featuring various animals. Here is the code snippet: $scope.animals = [ {value:'lion', name:'lion', description: 'lion'}, {value:'cat', name:'cat', ...

The function does not have a specified return value

I've been grappling with this issue for quite some time and I can't figure out what's causing the problem. In my code, I have a separate class called Database.js that handles MySQL functions, manages connections, queries, etc. My goal is to ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...