Javascript eval script tag

Can scripts be inserted with innerHTML?

In this tutorial, we will learn that can scripts are inserted with innerHTML.

There are various properties in JavaScript that help in working with the HTML of the current page. The innerHTML property in JavaScript is used to add the Html to the element. It also returns the content present in an element.

Scripts are the programs or codes of JavaScript that makes a webpage interactive and dynamic. We can add the script in the script tag on the same page or another JavaScript page linked with an HTML file.

The HTML is inserted in the innerHTML property for an element. But, the script cannot be inserted in the innerHTML property. If inserted in the innerHTML, it will neither be displayed on the page nor executed. The script in the innerHTML does not do anything on the webpage.

So, let us look at the script inserted with innerHTML and how to add the script to execute.

Inserting a script with innerHTML

The innerHTML is used to replace the content of the Html element with the Html content added to it. It is used for Html content and cannot execute a script with this property. The script added in the innerHTML is also not visible on the screen.

We cannot use the innerHTML for elements for the script. But we can add a script to an element by creating a script named element using the createElement method. We have to add a script inside it using innerHTML and then append it back to the element that has to add a script. In this way, we have to add the script to the script element first and then to the HTML element by appending it to an element.

Читайте также:  Как переключить php ubuntu

We are following the below syntax to insert a script with innerHTML.

Syntax

//A wrong way to add a script using innerHTML var element = document.getElementById(""); element.innerhtml= "  "; //A right way to add a script using innerHTML var script= document.createElement("script"); script.innerhtml="  "; element.appendChild( script );

We are following the above syntax to check whether can scripts are inserted with innerHTML.

Example

In the example below, we have to display the square of the number entered by the user in the input field. We have added the script in the innerHTML property of an element. But it is not a behavior of this property to execute the script like this. This script has become useless as it does not execute nor display on the screen. So, we have created a script element using the createElement property and added a script inside it using the innerHTML. At last, we have appended this script element to an element in the HTML element.

html> body> h2> Using the i> innerHTML property i> to insert a script h2> label> Enter a number: label> input type = "number" id = "number" name = "Number" value = "0" /> br> button id = "btn" onclick = "func()"> Submit button> div id = "div"> div> script> function func() < //Trying to add a script using innerHTML that will not execute var div = document.getElementById("div"); div.innerHTML = 'script> var 1 = document.getElementById('123').value; var square = value * value; document.getElementById('div').innerHTML ='Square of the number: ' + xyz; '; //Adding a script using innerHTML that will execute var script = document.createElement("script"); script.innerHTML = "var value = document.getElementById('number').value; var square = value * value; document.getElementById('div').innerHTML ='Square of the number: ' + square;"; div.appendChild(script); div.style.color = "red"; > script> body> html>

In the example, users can see that to execute a script using the innerHTML property, we must add it through the script element.

Inserting a script using eval() method with innerHTML

The eval() method is the method in JavaScript that takes the script as a string in its parameter. It will execute the string provided in the parameter as a JavaScript statement and return the script’s result. We have to insert the script in double or single quotes because this method provides the script as a string.

All the users can follow the syntax to use eval() method with innerHTML to insert a script.

Syntax

var element = document.getElementById(""); element.innerhtml= eval("");

Follow the above syntax to use eval() method in JavaScript.

Example

In the example, we have used the eval() method to execute a script inside an innerHTML property. From the user, we will take two inputs, showing the subtraction on the screen after clicking a button. The script for subtracting a number has been added inside an eval method in the innerHTML property.

html> body> h2> Using the i> eval() method i> to insert a script through innerHTML h2> label> First number: label> input type = "number" id = "number1" name = "First" value = "0" /> br> span>-span> br> label> Second number: label> input type = "number" id = "number2" name = "Second" value = "0" /> br> button id = "btn"> Substract button> div id = "div"> div> script> var element = document.getElementById('div'); document.getElementById("btn").addEventListener("click", func); function func() < element.innerHTML = eval("element.style.color = 'red'; var first = document.getElementById('number1').value; var second = document.getElementById('number2').value; var Substract = first - second; element.innerHTML = 'Subtraction of the two numbers is: '+ Substract;"); >script> body> html>

In the above example, users can see that we have used the eval() method to execute a string inside an innerHTML property of JavaScript.

In this tutorial, we have learned how scripts can be inserted with innerHTML.

Источник

Eval: выполнение строки кода

Встроенная функция eval позволяет выполнять строку кода.

let code = 'alert("Привет")'; eval(code); // Привет

Строка кода может быть большой, содержать переводы строк, объявления функций, переменные и т.п.

Результатом eval будет результат выполнения последней инструкции.

let value = eval('1+1'); alert(value); // 2
let value = eval('let i = 0; ++i'); alert(value); // 1

Код в eval выполняется в текущем лексическом окружении, поэтому ему доступны внешние переменные:

Значения внешних переменных можно изменять:

let x = 5; eval("x = 10"); alert(x); // 10, значение изменено

В строгом режиме у eval имеется своё лексическое окружение. Поэтому функции и переменные, объявленные внутри eval , нельзя увидеть снаружи:

// напоминание: режим 'use strict' включён по умолчанию во всех исполняемых примерах eval("let x = 5; function f() <>"); alert(typeof x); // undefined (нет такой переменной) // функция f тоже невидима

Без use strict у eval не будет отдельного лексического окружения, поэтому x и f будут видны из внешнего кода.

Использование «eval»

В современной разработке на JavaScript eval используется весьма редко. Есть даже известное выражение – «eval is evil» («eval – это зло»).

Причина такого отношения достаточно проста: давным-давно JavaScript был не очень развитым языком, и многие вещи можно было сделать только с помощью eval . Но та эпоха закончилась более десяти лет назад.

На данный момент нет никаких причин, чтобы продолжать использовать eval . Если кто-то всё ещё делает это, то очень вероятно, что они легко смогут заменить eval более современными конструкциями или JavaScript-модулями.

Пожалуйста, имейте в виду, что код в eval способен получать доступ к внешним переменным, и это может иметь побочные эффекты.

Минификаторы кода (инструменты, используемые для сжатия JS-кода перед тем, как отправить его конечным пользователям) заменяют локальные переменные на другие с более короткими именами для оптимизации. Обычно это безопасная манипуляция, но не тогда, когда в коде используется eval , так как код из eval может изменять значения локальных переменных. Поэтому минификаторы не трогают имена переменных, которые могут быть доступны из eval . Это ухудшает степень сжатия кода.

Использование внутри eval локальных переменных из внешнего кода считается плохим решением, так как это усложняет задачу по поддержке такого кода.

Существует два пути, как гарантированно избежать подобных проблем.

Если код внутри eval не использует внешние переменные, то вызывайте его так – window.eval(. ) :

В этом случае код выполняется в глобальной области видимости:

Источник

Оцените статью