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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to be better than the eval() answer by. In your opinion is your answer a better practice?
@DanJamesPalmer eval should be avoided in most cases (it is both dangerous and slow).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.