Tips for Troubleshooting External Evaluation Scripts

For a specific example, take a look at the haystack.js script from How Big is Your Haystack?

I've been searching for a solution and it seems that using the //# sourceURL=name.js comment is the way to go. However, I am struggling with the process of actually implementing this (maybe I'm just not getting it).

Most resources point to Debugging JavaScript, but unfortunately the demo there is broken due to a same-origin error. Other examples available do not offer much help when dealing with an external script like in this case.

I attempted to use Live Edit to add the sourceURL comment, but so far the eval script doesn't show up in the Sources tab.

Could someone walk me through the steps required to complete this task?

UPDATE: This has turned out to be quite an intriguing yet frustrating challenge. The website itself adds unnecessary complexity to the task with the following issues:

  • The haystack.js script contains document.write() statements which need to be removed before reloading the script to prevent clearing the DOM.

  • The author uses a peculiar form of code obfuscation. Therefore, any code modifications (including adding the sourceURL) must happen after removing the obfuscation but before the eval stage.

I managed to find a workaround. After loading jQuery into the page, I executed the following script:

$.ajax({
  url: '/js/haystack.js',
  dataType: 'text'
}).done(function(data) {
    // Remove document.write() statements and add sourceURL comment after deobfuscating
    var refactored = data.replace(/return d/, "return d.replace(/document\.write[^;]+;/g, '') + '\\n//# sourceURL=haystack.js\\n';");
    $('head').append('<script type="text/javascript">' + refactored + '</script>');
});

Now, haystack.js appears in the (no domain) tree of the Sources tab. Breakpoints can be set, however some strange behavior occurs. It seems that the DOM event handlers are still attached to the original script (breakpoints in reloaded script handlers are never triggered). Re-executing pageInit() reattaches the handlers to the modified script, but page updates remain unpredictable. It's unclear why this inconsistency persists. Even though I can step through the code and everything looks normal, the page updates seem delayed. Undoubtedly, the fact that the code violates many javascript best practices plays a role in this issue.

Answer №1

Curiosity sparked by this question led me to explore different methods. My journey began with Set breakpoints and debug eval'd JavaScript, which I then further expanded upon.

You can also check out the plunker

An alternative to using eval is inserting a script element into a document.

var js = "console.log('this is line 1');"
addCode(js); // Right now! Debuggable!

// Dynamically evaluate JavaScript-as-string in the browser
function addCode(js){
  var e = document.createElement('script');
  e.type = 'text/javascript';
  e.src  = 'data:text/javascript;charset=utf-8,'+escape(js);
  document.head.appendChild(e);
}

Subsequently, it will be visible in the sources tab:

For those preferring to use eval, remember to include the line //# sourceURL=dynamicScript.js at the end.

Check out this plunker

var js = "console.log('this is line 1');\n" +
"//# sourceURL=dynamicScript.js;"
addCode(js); // Right now! Debuggable!

// Dynamically evaluate JavaScript-as-string in the browser
function addCode(js){
  eval(js);
}

Take note that the script will appear under the (no domain) source folder.

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

Is it possible to determine if jQuery find returns true or false?

Snippet of HTML Code <div class="container1"> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> </div> <div clas ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

What is the reason behind every single request being treated as an ajax request?

Recently, I embarked on a new application development journey using rails 4.0. However, I've encountered an unexpected situation where every request is being processed as an ajax request. For instance, consider this link: =link_to "View detail", pr ...

What is the best method for securing my API key within the script.js file while utilizing dotenv?

My goal is to conceal my API key using dotenv. Interestingly, when I replace require('dotenv').config(); with my actual API key in the code as apiKey: process.env.API_KEY, it works fine despite not using process.env.API_KEY. I made sure to inst ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

I have come across this building error, what do you think is the cause of it?

My attempt to launch my company's React.js project, downloaded from Tortoise SVN, is encountering an issue. PS C:\Projects\Old EHR> yarn start yarn run v1.22.19 $ next start ready - started server on 0.0.0.0:3000, url: http://localhost:30 ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

ExtJs encounters missing files in directory - Error: Module '<path>modern-app-3 ode_modules@senchaextpackage.json' not found

I am currently in the process of setting up a new ExtJs project by following the instructions provided here. Upon completing the installation of ext-gen, I proceeded to create a new app using the command ext-gen app -a -t moderndesktop -n ModernApp3, but ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

Learn how to incorporate a consistent header and footer across multiple pages on a website with Node.js, ExpressJS, and either hbs or ejs templates

Creating a common header (navbar) and footer page to be included in multiple/several pages of a website. I want to create a dynamic website using Node.js and Express.js. The code for the navbar and footer will be placed in a common file named header.html ...

What is the best way to transfer global Meteor variables to templates and effectively utilize them?

I am in the process of developing a compact, single-page application game that emulates the dynamics of the stock market. The price and behavior variables are influenced by various factors; however, at its core, there exists a finite set of universal varia ...

Encountering a npm script error while running on a Windows operating

While using webpack to build my application, I encountered the following error message in the command prompt: [email protected] dev D:\Myprograms\java script\forkify webpack --mode development The error mentioned: Insufficient num ...

Next.js app encounters a BSON error when using TypeORM

Currently, I am in the process of integrating TypeORM into my Next.js application. Despite utilizing the mysql2 driver and configuring 5 data sources, I am encountering a persistent BSON error: ./node_modules/typeorm/browser/driver/mongodb/bson.typings.js ...