1

The powers that be have asked me to look into this and as much as I think it's not possible I want to be sure before going back to them. Don't ask me why they want this haha

They want to be able to use JavaScript that is defined in a variable. Let me explain...

Let's say you have this variable:

var testvar = "function dan() { alert('hello world'); }";

They want to be able to call dan() and have an alert popup in the web page. Something like this doesn't appear to be useable (of course).

var importjs = document.createElement('script');
importjs.src = testvar;
document.getElementsByTagName("head")[0].appendChild(importjs);

Any ideas or jargon I can use to explain why it's not doable. I believe it's essentially a cross origin issue. Our solution requires users to install software, which uses web sockets. This software performs a file GET for the JS and we then want to use the JS in the browser.

sideshowbarker
  • 72,859
  • 23
  • 167
  • 174
Dan James Palmer
  • 2,174
  • 6
  • 40
  • 65

1 Answers1

2

You should set the innerHTML of the script element to your String. The src of a script element should only be used to load an external script.

var testvar = "function dan() { alert('hello world'); }";
var importjs = document.createElement('script');
importjs.innerHTML = testvar;
document.getElementsByTagName("head")[0].appendChild(importjs);
dan();
Unmitigated
  • 46,070
  • 7
  • 44
  • 60