Using incorrect string as JavaScript argument

Currently, I am facing an issue with passing parameters elegantly in my code. I have a link for deleting items which looks like this:

<a href="javascript:confirmDelete('${result.headline}', ${result.id});">

The problem occurs when the result.headline includes characters such as ' or " that disrupt the JavaScript call. I attempted to use

${fn:replace(result.headline,"'","")}
to fix issues with ', however, I am looking for a way to URLEncode these characters to prevent them from breaking the JavaScript call. Any suggestions on how to address this without making changes to the backend?

Answer №1

Avoid placing inline JavaScript within elements, especially javascript: pseudo-URLs which (besides being considered harmful and should be avoided) are essentially JavaScript-inside-URL-inside-HTML. The recommended approach would be to take the headline and:

  1. Encode it as a JavaScript string literal. (By replacing \, ', control characters, and possibly Unicode characters, or using a JSON encoder for assistance.)
  2. Then, encode it as a URL.
  3. Finally, encode it as HTML.

It is preferable to include the data in the markup, where you only need to focus on basic HTML encoding like you do everywhere else to prevent cross-site scripting:

<a href="#" class="confirmdelete-${fn:escapeXml(result.id)}" title="${fn:escapeXml(result.headline)}">Delete</a>

and let the JavaScript extract them:

<script type="text/javascript">
    for (var i= document.links.length; i-->0;) {
        var link= document.links[i];
        if (link.className.indexOf('confirmdelete-')===0) {
            link.onclick= function() {
                confirmDelete(this.title, this.className.substring(14));
                return false;
            };
        }
    }
</script>

(there may be more efficient, concise, or cleaner ways to write the code above using utility functions or frameworks, and there's room for discussion on whether a link is the most suitable markup for this type of action, but that's the fundamental concept.)

Answer №2

Ensuring there are no newlines in the strings is crucial for this method to work effectively. All you have to do is double up on all backslashes and escape any single quotes.

Here's an example:

replace(replace(result.headline, "\\", "\\\\"), "'", "\\'")

Please note that the syntax used here may not be applicable in your server-side programming language; it doesn't seem familiar to me.

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

Tips for sending a Json array to a servlet

[DUPICATE] Here is the JSON code I am using for my POST request: var data_create = JSON.stringify($("#form_create_delegate").serializeArray()); alert("data_create content" + data_create); // console.log(data_create) $.ajax({ ...

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

What is the process for converting plain text into an image tag using the methods ".replace()" and ".html()"?

My goal is to customize this particular answer so that it can transform classic BCCode [img]{url}[/img] into an HTML image. In the code snippet provided, I have successfully implemented something similar with [b]text[/b]. However, when attempting to use [i ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Printing Strings in JavaScript IF Conditional Block

Hello there! I am looking for assistance with a JavaScript concept. Recently, I created some code where in the HTML file, there is a div element with an id of "GetID" where the string outputs are meant to be displayed. The JavaScript code looks something ...

JavaScript code that formats input prices, detects any formatting errors

Before jumping to conclusions, I want to clarify that I am not inquiring about the actual process of formatting the price. Instead, I am seeking guidance on where I may be going wrong or what steps I need to take in order to achieve the desired outcome. I ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

What is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Lack of Ajax query string parameters

To implement a functionality where clicking on a delete button in the UI triggers a service method that retrieves data from a database and displays it in a popup, I need to call a specific method in an Action class. The task id and command name (method nam ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

Showing VUE Content Delivery Network

Unable to render v-for with CDN in Vue.js const Gallery = { template: '{{$t('gallery')}} <img :class="[[item.class]]" v-for="(item, index) in carousel" :src="[[item.img]]" alt="img" />' } c ...

Error: The function initMap() is not recognized in the Google Maps API

I have been experimenting with the Flickr API and I'm currently working on asynchronously loading images along with their metadata. To accomplish this, I have a script that utilizes three AJAX calls: $(document).ready(function() { var latLon = { ...

Parse multiple JSON files, manipulate their contents, and store the updated data

I'm currently working on implementing this functionality using Gulp. Locate and access all files with the extension .json within a designated directory, including any subdirectories. Perform modifications to the files in some manner, such as adding ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Creating a span element to replace the list item class in a JavaScript Modal Pop-up

I recently set up a portfolio website that showcases my projects. When you click on a project, a modal window opens with a carousel gallery inside. On my .html page, the projects are organized like this: <li class="Project" data-modal="myModal_1"> ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

Showcasing an HTML table using Material-UI

Currently, I have a list of issues being displayed in my browser using the material-ui code below: <Paper className={classes.root} elevation={4}> <Typography type="title" className={classes.title}> All Issues </Typography> ...