What is the process for retrieving a script from an endpoint and utilizing it as a request response?

Currently, I am working on a project where we are required to retrieve a script from an endpoint for consumption. The API designed for the web returns a self-invoking function that sets a variable. The request header specifies the content-type as application/javascript, and my goal is to extract this result from the endpoint and incorporate the variable into my application.

To illustrate this concept further, let's consider the following script:

const Script = (() => {
  return {
    some: "method",
    another: "method",
  };
})();

This script is provided by an endpoint for use in a web browser through the following script tag:

<script src="https://example.com/index.js"></script>

However, my objective is to access this script/variable for integration into my React Native application, as shown here:

fetch("https://example.com/index.js", { method: "GET" }).then((response) => {});

The issue arises when the response from the request does not align with my requirements. While I can convert it to a Blob, I am unsure about how to parse this Blob into a JavaScript function or a similar entity.

Answer №1

By employing the Function feature that utilizes eval internally, the challenge was successfully resolved.

Upon receiving a Blob script as a response, it was necessary to convert it into a string for processing. I achieved this by creating a Response instance using the Blob and subsequently utilizing the text method.

Once the string was prepared, it involved crafting a self-invoking function to transform a defined variable. This required editing the string to construct a function that would return the variable.

Finally, a function was created and executed to retrieve the desired object into a variable.

fetch("https://example.com/index.js", { method: "GET" }).then((response) => {
  new Response(response._bodyBlob).text().then((text) => {
    const modifiedString = `${text}; return Script`;

    const scriptObject = new Function(modifiedString)();
    ...
  });
});

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

Display the date that is 3 days after the selected date from the Date Picker in the text field

This is the date picker code I am currently using: var d = new Date(); $(function () { $("#datepicker").datepicker({ minDate: d, dateFormat: 'mm-dd-yy' }); }); I want to enhance this functionality so that when a date is ...

Is an Ajax powered loading feature used in transitions between pages?

I recently came across this interesting website: It appears that they have implemented a clever technique where new content is dynamically loaded using AJAX, giving the impression of seamless navigation. Additionally, they have succeeded in hiding the bro ...

Oops! There was an error: Uncaught promise rejection: TypeError - Unable to access 'subscribe' property of null object (Ionic Angular)

I encountered an issue in my angular ionic project. When I log in, the first page displays the error "ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null." However, upon reloading the page, the error disappears ...

Injecting services and retrieving data in Angular applications

As a newcomer to Angular, I am trying to ensure that I am following best practices in my project. Here is the scenario: Employee service: responsible for all backend calls (getEmployees, getEmployee(id), saveEmployee(employee)) Employees components: displ ...

Utilize Google Autofill to easily populate address fields in a form

I've come across several autofill address codes, but I'm looking to integrate a Post function that would allow me to post the obtained data to a PHP page. Is there anyone who can assist with the javascript or HTML code to achieve this? HTML Cod ...

Retrieving XML using JavaScript with AJAX

Having trouble retrieving XML data using JavaScript and Ajax. The script takes too long (up to 45 seconds) to collect the data from the database and return it as XML. Everything works fine when loading the data locally, so no issues with cross-domain. An ...

Strategies for managing data sharing between PHP and JavaScript

Today, I am seeking your valuable advice. Currently, I am working on a significant legacy project at my company, which involves finding a solution to share constants between our PHP 5 back-end (MVC architecture, no framework) and our front-end with Angula ...

Reversing the order of items in Angular 2 for repetition

Is there a way to display search items in reverse order? This is what I have attempted so far: let newSearchTerm = this.getItem(this.searchHistoryKey) newSearchTerm.push({ 'q': this.searchTerm }); this.setItem(this.searchH ...

Error: The function preciseDiff is not recognized by moment

Encountering an error message: "TypeError: moment.preciseDiff is not a function. I am facing the same issue, wondering if there is a solution or alternative available. I have version 2.24.0 of moment installed. moment-precise-range-plugin In addition, I ...

How to make divs occupy the entire space of a parent div?

I've been scouring the website for a solution, but nothing I've found has been helpful. I'm attempting to create a grid within a containing div where a default (and eventually user-specified) number of divs will fill up the space. I'm t ...

Apply a single CSS bounce animation to a specific div when clicked

I have implemented a CSS map pin with some CSS3 animations. You can check it out here: https://jsfiddle.net/xg7xfzeq/ body { background: #e6e6e6; } .pin { width: 30px; height: 30px; border-radius: 50% 50% 50% 0; background: #00cae9; position ...

"Optimize Magellan Sidebar for Mobile Devices by Relocating it to the Bottom of the Page

After spending a week working with Foundation 5 framework, I'm curious if there is a straightforward way to make my magellan sidebar shift to the bottom of the page when viewed on mobile or tablets. <div data-magellan-expedition="fixed"> <di ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

Is there a way to determine if a div is positioned 100px from the bottom edge?

When using the sticky class to stick a div, I encountered an issue where it sticks correctly from the top but overlaps the footer at the bottom. https://i.sstatic.net/28A3A.jpg Here is the HTML code: <div class="tab-content"> <div role="tab ...

Looking for assistance with transforming JSON data into a three-tiered multidimensional array using JavaScript

Seeking guidance on converting JSON data into a 3-tier multidimensional array using JavaScript. The JSON data I am working with is structured as follows: [ {'City':'Philadelphia','State':'Pennsylvania','Countr ...

Error: "Access-Control-Allow-Origin" header is missing in Firebase Function

I have encountered an issue with my firebase functions GET request. While I am able to receive data using Postman, I am facing difficulties when trying to fetch data from my front-end application. Upon accessing the endpoints, I am seeing the following er ...

Tips for pulling out specific keys from a typed object using an index signature

TL;DR Query: How do I create a type converter in TypeScript that extracts the defined keys from objects typed with index signatures? I am looking to develop a type "converter" in TypeScript that takes a type A as input and outputs a new type B with keys ...

I'm looking to transfer an integer to and from JSON using Java. Can anyone guide me on how to

I have been working on an API that processes HTTP requests and returns JSON reports. To test the functionality, I have experimented with both Java (using HTTPUrlConnection) and Python (using requests). The API itself is developed in Java Spark. I find Pyth ...

Is there a way to link dynamic server fields with VueJS?

How can I bind data posted by the server with Vue.js in order to display the data instead of field names? <script> module.exports = { data: function () { return { filedNameFromServer: ['{{filed1}}' ...

Is a Promise nested within another Promise?

My current task involves retrieving the lat/long of 2 addresses using promises. Once this initial promise is resolved, I need to parse a file that correlates with these lat/long coordinates. Everything works as expected and I can handle the values in the ...