Is there a way for me to intercept JavaScript code before it runs on Chrome?

Looking to develop a Chrome extension for the developer tools that can intercept JavaScript code on a current web page prior to compilation or execution by the browser. I aim to instrument the JS code before it runs in the browser.

Could someone assist with how this can be achieved?

Thank you in advance.

Answer №1

There is no direct way to intercept the loading process itself, but by leveraging the behavior of scripts with custom types, it is possible to manipulate the document loading sequence through a clever workaround.

By invoking window.stop, the document loading can be halted abruptly at the outset, indicating that the full document has not been loaded successfully.

Subsequently, an XHR request can retrieve the document content for further modification. Using search and replace techniques, all script elements in the document can be rendered inactive by assigning them a specific type before injecting the modified content back into the document flow.

window.stop();
var request = new XMLHttpRequest();

request.open('GET', location.href);
request.onload = function(event) {
  var html = request.responseText
    .replace(/type=\"text\/javascript\"/g, '')
    .replace(/<script/g, '<script type="x-instrument/javascript"');

  document.open();
  document.write(html);
  document.close();
};

request.send(null);

At this stage, all scripts have been effectively neutralized, allowing for the implementation of a basic sequential loader as illustrated below:

setTimeout(function next(index) {
  var script = document.scripts[index];
  if (script == null) {
    return setTimeout(callback, 0);
  }

  if (script.hasAttribute('src')) {
    var request = new XMLHttpRequest();
    request.open('GET', script.getAttribute('src'));
    request.onload = function() {
      var code = instrument(request.responseText);
      eval(code);

      setTimeout(next, 0, ++index);
    };

    request.send(null);
  } else {
    var code = instrument(script.textContent);
    eval(code);

    setTimeout(next, 0, ++index);
  }
}, 0, 0);

This approach allows any page to undergo instrumentation simply by injecting the aforementioned script at the beginning of the document.

If preferred, the script can also be loaded as a content script within a Chrome extension, ensuring that the run_at attribute is set to document_start.

{
  "manifest_version": 2,
  "name": "instrument",
  "version": "0.0.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["instrument.js"],
      "run_at": "document_start"
    }
  ],
  "web_accessible_resources": [
    "instrument.js"
  ],
  "permissions": [
    "tabs", "<all_urls>"
  ]
}

Example

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

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

Using Three.js to rotate a camera-followed sphere in the scene

Currently, I'm developing a Three.js scene with a toy concept where I aim to track a sphere using a camera [demo]. However, I am facing an issue wherein I can't seem to get the sphere to "roll" without causing the camera to also rotate along with ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

The Jquery animate function is not compatible with the transform property

I am facing an issue with the Jquery animate function. Despite trying various solutions, I have been unable to get it to work. Below is the HTML code that I have used: <!DOCTYPE html> <html lang="en"> <head> <meta cha ...

method for sorting labels in Select element in ReactJS

Hey there, I'm facing an issue with the code snippet available here. I would really appreciate it if you could assist me in resolving this problem. This is the code: import React from "react"; import { Select } from "antd" ...

Steps to enable Nodemailer to execute a separate .js script

Currently, I have the main nodejs server file named myserver.js const express = require("express"); const app = express(); const nodemailer = require("nodemailer"); const port = 80; const vectorExpress = require("./node_modules/@ ...

Adjust the opacity of a div's background without impacting the children elements

I am currently working on a dynamic content display in my HTML page using some knockout code. The setup looks like this: <section id="picturesSection" class="background-image" data-bind="foreach: { data: people, as: 'person'}"> <div ...

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...

Guide on adding user input values (type=text) into HTML using JavaScript function outcome

I'm looking for a way to use the output of a JavaScript function as the value for an input field in HTML. Currently, I have a JavaScript function that generates a random string: function generateRandomString(length) { let result = ''; ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Execute a Vue.js script once all Axios calls have been resolved

In this scenario, it is necessary to execute the carResult function only after all axios requests have been completed. Placing it inside the success method of method2 won't work because the component ends up executing the code twice. It would be great ...

Using the $.each method instead of a traditional for loop

validateScaledIntegerNumberGridFields: function(frm) { var fields = $('.scaledInteger', frm); var result = true; $.each(fields, function(index) { var scale = $(this).data("scale"); ...

Executing multiple HTTP requests in parallel with AXIOS and retrieving the responses even if one of the requests fails

I am currently working on optimizing server get requests to run concurrently. To achieve this, I have developed the following function. Issue The problem arises when one request fails, causing me to lose track of the responses from the other requests. e ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

Explore innovative ways to display mathematical equations dynamically on the browser using NextJS version 13.3.0 or consider alternative solutions for showcasing math content with

I'm currently working on developing a web application that allows users to input LaTeX expressions, which are then dynamically displayed in another div or updated within the same input field. After some experimentation with Mathquill and NextJS v13.3 ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

How to perfect the alignment of TimePicker in angular UI

I'm dealing with the code below: <ul class="dropdown-menu custom-scroll dropdown-label custom-width" role="menu" aria-labelledby="btn-append-to-body" ng-show="!display" > <li role ...

Updating Bootstrap modal content based on button clickExplanation on how to dynamically change the content

I am looking to dynamically change the content displayed inside a modal based on the button that is clicked. For example, clicking button one will only show the div with the class 'one' while hiding the others. $('#exampleModalCenter&a ...