Imagine a code:
<div id='teste' data-conteudo="funcao()"></div>
I want to get the attribute "% cc" from the "function ()" function to be triggered, as if it were a value of the onclick attribute.
Imagine a code:
<div id='teste' data-conteudo="funcao()"></div>
I want to get the attribute "% cc" from the "function ()" function to be triggered, as if it were a value of the onclick attribute.
function funcao()
{
alert("Dolly guaraná");
}
var dc = document.getElementById("teste").getAttribute("data-conteudo");
eval(dc);
<div id='teste' data-conteudo="funcao()"></div>
Credits Jefferson Quesado for reminding me
If a malicious user enters your site and does so
function pegar_todos_os_usuarios(){
return [
{name:"zé ramalho", pass:"ramalho"},
{name:"Largato", pass:"mosca"}
];
}
function funcao()
{
alert("Dolly guaraná");
}
var dc = document.getElementById("teste").getAttribute("data-conteudo");
eval(dc);
<div id='teste' data-conteudo="alert(JSON.stringify(pegar_todos_os_usuarios(), null, 4))"></div>
Now imagine the mess he can make
Summarizing
Since this is a string, with each function called, you can check if it's what you want, eg
function pegar_todos_os_usuarios(){
return [
{name:"zé ramalho", pass:"ramalho"},
{name:"Largato", pass:"mosca"}
];
}
function funcao()
{
alert("Dolly guaraná");
}
var btn = document.querySelector(".opa");
btn.onclick = function () {
var dc = document.getElementById("teste").getAttribute("data-conteudo");
if (dc === 'funcao()') {
eval(dc);
} else {
alert("Falha");
}
}
<div id="teste" data-conteudo="pegar_todos_os_usuarios()"></div>
<button class="opa">EXECUTAR</button>
I would not use eval
for security reasons. Instead I would create a new function that would call the funcao()
function using new Function(nome_da_função())
:
function funcao(){
console.log("função executada");
}
var atr = document.getElementById("teste").dataset.conteudo;
var funcao2 = new Function(atr);
funcao2(); // outro nome que chama funcao()
funcao(); // nome original
<div id='teste' data-conteudo="funcao()"></div>
It would only happen that funcao()
would have another name: funcao2()
, while also being funcao()
.