skip to Main Content

I was debugging my NodeJS app when I came to this huge fact : Using jQuery, a simple

$.get(code_url)

Where code_url is an URL toward javascript code on the server, does executes the code.

What is expected is :

$.get("script.js", function(data) {
    // data contains the content of 'script.js' as a string
    // We can choose either to :
    // - Append it to the DOM
    // - Evaluate it using eval()
    // - Store it for later use
});

But still, even with nothing done in the callback, code is indeed executed.

I tried to recreate a server almost empty, with just a few lines of code to make sure that it does not come from my project. Even with a total of a dozen of lines, I can reproduce.

NodeJS server :

const express = require('express');
const App = express();
App.use(express.static('www'));
App.listen(5000);

index.js (executed by the index.html)

$(document).ready(function() {
    $.get("utils.js")
});

utils.js (served as static in www/ by the server)

console.log("Hello World");
let a=1000;
console.log(Math.PI*a);

And BOOM, code executed :
Google Chrome console showing code execution

NB: Issue seems to happen only on local server, but still I think it’s quite a serious issue. I just cannot manage to download any piece of code without having it executed on the fly… Come on. Did I find a HUGE jQuery bug ?

Tested on

  • jQuery 3.6.3 and 3.7.1
  • Google Chrome (Version 123.0.6312.122 (Official Build) (64-bit))
  • Linux Ubuntu 22.04

2

Answers


  1. Chosen as BEST ANSWER

    Answer given by @Pointy :

    $(document).ready(function() {
        $.get("utils.js", function(data){
            
        }, "text/plain")
    });
    

    Prevents the code from being executed


  2. The server must be returning the Content-type: text/javascript header.

    If you don’t specify the dataType argument to $.get(), jQuery infers the type from the Content-Type header. text/javascript corresponds to dataType = "script". And from the documentation:

    "script": Evaluates the response as JavaScript and returns it as plain text.

    In other words, $.get("script.js") is effectively equivalent to $.getScript("script.js")

    If you want to retrieve the source code without evaluation, specify the text dataType explicitly:

    $.get("script.js", "text");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search