Can JavaScript be utilized to scan JavaScript code and identify all the URLs that the code is designed to access?

Suppose I am working with a complete JS script stored in a string variable. Instead of running the entire script, my goal is to evaluate its code to identify the URLs it would attempt to retrieve via Ajax if executed.

While I could use regex to search for URLs within the code as text, this method may not uncover hidden URLs that have been obfuscated using functions like replace().

The solution needs to be implemented using Javascript.

Can anyone offer a hint on how this task could potentially be achieved?

Edit: To provide context, my current project involves creating a Greasemonkey script to filter out Facebook spamming scams from userscripts.org's script listing. I have already implemented a basic text search for common Facebook Ajax URLs used in scams, but scammers are finding ways to circumvent it. I need a reliable way to capture all Ajax URLs for inspection, regardless of how they have been manipulated and modified using string functions. More information can be found at .

Answer №1

If you're looking to intercept all AJAX calls, this topic may be of help: intercept all ajax calls?

Instead of relying on JavaScript frameworks, you can redefine XHR for custom behavior:


var ajax_urls = new Array();
var XHR_backup = new Array();
XHR_backup.open = XMLHttpRequest.prototype.open;
XHR_backup.send = XMLHttpRequest.prototype.send;

// Customize XHR behavior
(function(XHR, ajax_urls) {
    "use strict";

    var open = XHR.prototype.open;
    var send = XHR.prototype.send;

    XHR.prototype.open = function(method, url, async, user, pass) {
        ajax_urls.push(url);
    };

    XHR.prototype.send = function(data) {
    }
})(XMLHttpRequest, ajax_urls);

// Evaluate your script
eval(resultScript);

for (var i = 0; i < ajax_urls.length; i++) {
    alert('Hey, my super XHR fetched ' + ajax_urls[i] + ' !!');
}

// Restore initial XHR behavior
XMLHttpRequest.prototype.open = XHR_backup.open;
XMLHttpRequest.prototype.send = XHR_backup.send;

Edit: I have not tested this code snippet yet, so I look forward to hearing your feedback.

Edit2: Confirmed working after testing! Check it out here: http://jsfiddle.net/3qVUP/1/

Answer №2

If the entire content is stored in a variable, it can be treated as a string which allows for parsing to extract specific information. Utilizing Regular Expressions (RegEx) can help achieve this effectively. Explore RegEx here:

Here is an example of a RegEx pattern to identify URLs:

^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$

Regarding Comments

To handle multiple occurrences of these strings, they can be concatenated within a BuildString() function to create a single string result. The concatenated variable can then be subjected to regex operations to extract URLs.

For example:

function Concatenation() {
    var _strOutput = "<script>var x = 0; x += " + GetVariableIterator() + "; return x; </script>";
    return _strOutput;
}

function FinalResult() {
    var _strCombined = Concatenation();
    // Apply Regex and process URLs accordingly
}

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

A guide to extracting the Jquery Version from the Chrome browser console while browsing webpages and transferring it to the Eclipse Java console using Selenium

Is there a way to retrieve the Jquery Version from Chrome browser console for webpages and transfer it to eclipse Java console using selenium? Try this command: $. ui. version https://i.sstatic.net/3bxA1.png ...

Tips for locating a key within an object that houses a specific value in its array

In my Coffeescript code, I have created the following Javascript object: urlSets = a: [ 'url-a.com' 'url-b.com' 'url-c.com' ] b: [ 'url-d.com' 'url-e.com' 'url-f.com&a ...

What should be placed in the form action field if the router.post() method includes a parameter such as :id?

I'm struggling with how to properly submit data to my update form and what needs to be entered in the action field, especially considering the router.post includes an :id parameter. Below is the relevant code snippet: router.post('/gymupdate/:id& ...

Prevent the div from moving beyond the boundaries of its container while anim

After experimenting with a javascript image panner that I put together from various code snippets, I have decided to switch to a simpler approach. However, I need some guidance on a few things. Below is the code for the left and right buttons: <div id ...

Transform a one-dimensional array arranged in ASCII order into a hierarchical array structure using Javascript

Consider the array of objects below, sorted by the code property in ascending ASCII order: var codes = [ { code: '01' }, { code: '0101' }, { code: '0102' }, { code: '010201' }, { code: '0103 ...

Issue with updating overall expenditure functionality

I'm currently in the process of developing a straightforward shopping cart with the help of simpleCart.js. Up until now, I've managed to successfully showcase items, add them to the basket, and proceed to checkout. However, my next challenge inv ...

Guide to creating a React Hooks counter that relies on the functionality of both a start and stop button

I am looking to create a counter that starts incrementing when the start button is clicked and stops when the stop button is pressed. Additionally, I want the counter to reset to 1 when it reaches a certain value, for example 10. I have tried using setInte ...

When working on a REST APIs project with ReactJS fetch and NodeJS, I am encountering difficulties in reading authorization headers on the server side

I'm having issues retrieving headers on the server side using ReactJS fetch to call an API on the front end. In my old project, this functionality was working perfectly fine. I'm puzzled as to why it's not working now, especially since I hav ...

Transmitting data as an array using JQuery

$('[data-toggle="mftapproveCheck"]').click(function () { var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get(); //alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

JavaScript's sequential addition of nested arrays

Having trouble adding together 4 nested arrays in JavaScript. The arrays are structured like this: x = [[Array1(9)], [Array2(9)], [Array3(9)], [Array4(9)]] I am looking to "zip" them together and add the values. For example, I want to add Array1[0] with c ...

In Javascript, the assignment of a custom property continues indefinitely instead of occurring just once

Currently, I have a JavaScript code snippet where I am attempting to create a promotion field within each of my promotion items. However, I am encountering an issue where it keeps nesting itself endlessly, whereas I only require it to contain one reference ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

Erase a chat for only one user within a messaging application

Currently, I am in the process of building a chat application using nodejs and mongodb. In order to structure my database properly, I have created two models: conversation and messages. Message.js conversationId: { //conversationID }, body: ...

Continuous scrolling feature for dynamically loaded content via ajax requests

Currently, I am performing a WP_Query on page-a.php. This specific page contains a div named target where the content of page-b.php is loaded into. Page-a represents a custom template while page-b is an archive page. The layout structure on page A can be ...

The iron-session package does not export the path ./next/dist from the package

I am encountering an issue while using iron-session. Below is the code snippet causing the error: import { withIronSessionSsr } from 'iron-session/next/dist'; ... export const getServerSideProps = withIronSessionSsr(async function ({ req, r ...