0

i have the following problem. I have a div like the following:

<div id="1234">
[...........]
</div>

The main task was to have into a function, a variable with this form:

var locations=[[...........]];

So, the html content of the above div, i've got it into specific function, with following code:

var location= document.getElementById("1234").innerHTML;
var locations = eval('['+location+']');

With above codes, i have the wanted result, that is a variable, as i said before, like the following:

var locations=[[...........]];

This means that with eval(); the code is working good in the case that inside a div i have only html code.

But, for a more difficult case, what if inside div i have a javascript that write the same result:

<div id="1234">
<script>
document.write(&quot;&lt;script src=\&quot;/feeds/posts/summary/-/<data:content/>?max-results=3&amp;orderby=published&amp;alt=json-in-script&amp;callback=map_locations\&quot;&gt;&lt;\/script&gt;&quot;);
</script>
</div>

If i use the same codes

var location= document.getElementById("1234").innerHTML;
var locations = eval('['+location+']');

code is not working, and console log shows the following

VM8144:2 Uncaught SyntaxError: Unexpected token <
    at mainMap ((index):982)

Thanks a lot for your time....

  • your code is being escaped ie. `"`, `<`, etc. – Leo Jun 14 '19 at 21:02
  • 1
    the innerHtml you're trying to eval in your last example is not a valid JavaScript syntax. What do you expect exactly? your example doesn't help to understand your first need – boly38 Jun 14 '19 at 21:02
  • I'm trying to make a variable (var locations) that will get dynamically content from json feed javascript...The var locations, in order to work into a function, must have this type of content "var locations=[[elements of first p.o.i in map], [elements of second p.o.i in map],....]; So as first attempt, i wrote a code into a div and i've got it with var location= document.getElementById("1234").innerHTML; – Loukas Triantafyllopoulos Jun 14 '19 at 21:08
  • 1
    Try `innerText` instead of `innerHTML`. – zero298 Jun 14 '19 at 21:36
  • @zero298 or better, `textContent`. If necessary, remove the script elements by DOM manipulation. – Bergi Jun 14 '19 at 21:40
  • No matter what you do, understand that this is a direct route to XSS and script injection attacks. Please take whatever precautions and tell everyone involved that this is a complicated issue and needs careful planning. – zero298 Jun 14 '19 at 21:42
  • If you're processing JSON, use `JSON.parse()`, not `eval()`. – Barmar Jun 14 '19 at 22:11
  • See also [why is document.write bad](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Barmar Jun 14 '19 at 22:12
  • Thanks a lot for your help and these useful advices....With .innerText that i had in mind it's working.....Thanks for your time! – Loukas Triantafyllopoulos Jun 16 '19 at 14:21

0 Answers0