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);
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
Answer given by @Pointy :
Prevents the code from being executed
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 todataType = "script"
. And from the documentation: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: