The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json.

After examining the JSON format using

console.log(JSON.stringify(data))
, I discovered that the content included a script block:

{
    "content": "<script type=\"text/javascript\">console.log(\"test\");</script>"
}

To display this content dynamically, I created a div with the class of "content" based on the AJAX response:

var content = document.createElement("div");
content.setAttribute("class", "content");
content.innerHTML = data.content;

Subsequently, I appended this content div to an existing div on my site.

existingDiv.appendChild(content);

However, upon inspecting the source in Google Chrome's developer tools, I noticed that the script within the content was not executed. Even though it appeared as a DOM node, the script did not run successfully.

I explored options such as eval() but wished to avoid it due to security concerns. Additionally, the content could potentially include other HTML markup along with script blocks.

Seeking advice on how to resolve this issue and execute the dynamically added JavaScript block, I am open to jQuery solutions as well.

Answer №1

One approach could be to employ the new Function() method like this:

$(document).ready(function(){
   var script = "window.alert('hi')";
   new Function(script)();
});

The reason why your script might not be running, as mentioned by @Pointy (with a workaround), can be demonstrated with the following code snippet:

<script type='text/javascript'>
$(document).ready(function()
{
    $("<script type='text/javascript'>window.alert('hi');<\/script>").appendTo(document.body); // this will work

    var container = document.createElement("div"); // this won't work
    container.innerHTML = "<script type='text/javascript'>window.alert('hi');<\/script>";
    document.body.appendChild(container);

    var script = document.createElement("script"); // this will
    script.innerHTML = "window.alert('hi');";
    document.body.appendChild(script);
});
</script>

UPDATE: included a requested performance test: http://jsperf.com/eithed-hvsa

Answer №2

One way to load JavaScript code dynamically is by using the $.getScript() method. This method is simple, cacheable, and straightforward :

Check out more information here: http://api.jquery.com/jQuery.getScript/

(Please remember to update your server script that generates the JSON containing the JavaScript code and change headers accordingly)

Answer №3

When using the .innerHTML method, keep in mind that any <script> tags will not be evaluated by the browser.

To execute JavaScript code, it's recommended to send it as a string without <script> tags. This way, you can easily use the eval() function.

Edit: If you're working with jQuery and utilize the $(something).html() method to add content directly to the DOM element, instead of just setting innerHTML, jQuery will actively evaluate any <script> tags within the content.

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

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Implementation of the WCF POST method

I am currently working on a WCF service that communicates with an SQL server database from a mobile application. One of the methods in this service is responsible for creating bookings. public void CreateBooking(Booking booking) { ...

Creating a jquery DataTable from HTML generated by angular $sce can be done by following these steps

I have created an Angular controller that takes data and generates an HTML table from it. The generated table is being displayed on the page. Now, I want to apply jQuery data tables using that scope variable. The variable contains the HTML code of the tabl ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

Chrome's behavior of reducing the width of inline elements when the content is dynamic

Upon opening the specified URL in Google Chrome, an issue can be observed where on the initial load everything appears fine. However, upon refreshing, the width of the three items at the top (Bedingungen, Preise, and So geht's) collapse. This seems to ...

Prevent the button from being enabled until the file input is updated

I want to create a form with an input file for uploading photos, but I need the submit button to be disabled until the input file has a value. Additionally, there are other validations that will also disable the button. Here is the structure of my HTML fi ...

I have my doubts about whether I am implementing the recapcha API correctly in a React application

I implemented the recapcha API in order to prevent bots from submitting posts on a forum site. As a new developer, I'm not sure if this is a real threat or not, as the users are limited to a maximum of 3 posts before they have to pay for more. I' ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

trigger opening a bootstrap modal programmatically

I have a modal setup using Bootstrap with the code below: <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true" > &l ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Filtering out specific properties in an array using Angular

I am facing an issue with my Angular filter when inputting text for a specific list. initialViewModel.users = [ {user: 'Nithin',phone: 'Azus', price: 13000}, {user: 'Saritha',phone: 'MotoG1',price: 12000}, {user: ...

end the node.js automated testing process

I'm currently using Jasmine and Zombie JS to create automated tests. I have integrated Drone.io for Continuous Integration, and the tests are executing successfully. However, there seems to be an issue where after passing the tests, the process does n ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

Troubleshooting: Issue with Jquery background not functioning correctly

I have a nested while loop set up in my code. Within the inner loop, I am trying to hide a table row (tr) containing some information. When I click on a button with a class of 'toggle', I want to change the display CSS property and background col ...

Text Parallax Effect

For my website, I am interested in incorporating a unique parallax effect. Instead of just fixing a background image and allowing scrolling over it, I want to apply this effect to all of the content on my site. The website consists of a single page with m ...

Sustain unbroken websocket connection with Discord using Node.js

I've been working on developing a Discord bot using the raw API, but I've encountered an issue where the bot stops functioning after some time. I suspect that this is due to neglecting to maintain the websocket connection. How can I ensure that ...