How to activate a function by an attribute?

1

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.

    
asked by anonymous 02.03.2018 / 01:53

2 answers

1

function funcao()
{
  alert("Dolly guaraná");
}

var dc = document.getElementById("teste").getAttribute("data-conteudo");

eval(dc);
<div id='teste' data-conteudo="funcao()"></div>

XSS

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

Avoid eval()

How to avoid

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>
    
02.03.2018 / 02:00
3

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() .

    
02.03.2018 / 02:16