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

Incorporating external .js files from a different server using node.js

Is it possible to include .js files from another server into a node.js program? I cannot simply use require('./local_file.js') to fetch files over the Internet like this: require('http://www.server.com/path/file.js'); I attempted usin ...

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

Rendering images in Next.js version 10

Just recently, Next.js version 10 was launched featuring the latest Image element, making it a great asset for websites that heavily rely on images! When I receive an HTML response from the server, it looks something like this: HTML = "<div> &l ...

Using JQuery to fill an HTML dropdown menu with data from a JSON file

I've been struggling with this issue for a while and despite reading through other posts, I still can't seem to get it to work. My problem lies in populating a drop down menu with JSON data. Although the drop down menu appears on my HTML page, i ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

Instructions for making a crossword-inspired grid using a high quantity of divs or alternative elements

I am looking to create a grid on the screen of a web browser or mobile device, with each grid item containing just one letter. It's similar to a crossword puzzle, but taking up most of the screen. I've tried using divs for this purpose, but it se ...

Getting console data in AngularJS can be achieved by using the console.log()

This log in the console is functioning correctly. Is there a way to retrieve this information for the HTML? ProductController.js $scope.selectedProduct = function(product) { console.log(product.post_title); console.log(product.ID); console.l ...

Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component : <script> export default{ props:['search','category','shop'], ... methods: { getVueItems: function(page) { this.$store.disp ...

Utilizing AngularJS within a Captive Network Assistant (WISPr) on iOS and MacOS devices

In my past experiences with projects, it has been observed that Apple's Captive Network Assistant (also known as WISPr client) operates with a restricted browser. For further information, you can refer to How can I debug the browser in Captive Portal? ...

The event to close the HTTP connection in the Node server always triggers

I want to set up a close event that triggers before the server shuts down. To achieve this, I have implemented the following code: var express = require('express'); var app = express(); var http = require('http').Server(app); var list ...

Updating items within an array in a MongoDB collection

I am facing a challenge where I have to pass an array of objects along with their IDs from the client-side code using JSON to an API endpoint handled by ExpressJS. My next task is to update existing database records with all the fields from these objects. ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

Learn how to retrieve information using the dash operator in ReactJS

I find it a bit amusing, but I'm encountering an issue. Can anyone lend me a hand with this? So, I'm using an API to fetch some data and it appears that the response from the API is in this format: start-time:2323232 end-time:2332323 Now, when I ...

What is the best way to cache node_modules when package.json remains unchanged during yarn or npm install within a Docker build process?

A Dockerfile for a node application is structured as follows: FROM node:8.3 ENV TERM=xterm-color NPM_CONFIG_LOGLEVEL=warn PATH="$PATH:/usr/src/app/node_modules/.bin/" WORKDIR /usr/src/app ADD . /usr/src/app RUN yarn install --frozen-lockfile --ignore-plat ...

Issue with Sequential Drop Down List Functionality in ASP.Net MVC View Page

I am currently in the process of migrating code from one project to another. Although the code works fine in the original project, it is not functioning properly in the new one. I’m uncertain if something was overlooked on my end. Within this code, ther ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...