0

Desired output

<script type="text/javascript">
var = {
//myobject
}
</script>

Current thinking

var fileRef = document.createElement('script');
fileRef.setAttribute('type','text/javascript');
var = { //blahblahblah }
fileRef.setAttribute('innerHTML', var); << this is wrong
document.head.appendChild(fileRef);

Ideally I need to use something similar to innerHTML to inject the variable inside of a script tag

This is Janky but the client is demanding to edit the Object inline in optimizely so my hands are tied

1
  • I eventually convinced the client this was a terrible idea based on a terrible requirement and now they happily edit the object in an external file which I load through optimizelys jank script loader. Commented Sep 26, 2018 at 3:40

1 Answer 1

1

If the only thing you want to do is to add an JavaScript object onto the global namespace, and the content inside is strictly restricted to strings, numbers and booleans, then you can do that safely by:

let userEnteredString = '{"foo": "bar"}';
window[keyName] = JSON.parse(userEnteredString);

If it can contain values other than literals for the aforementioned types, then you can use the unsafe eval method (not recommended!):

let existingValue = "bar";
let userEnteredString = '{"foo": existingValue}';
window[keyName] = eval(`(${userEnteredString})`);  // not safe, only use this when
                                                   // absolutely needed

Note that these two snippets will not modify any script tags, though they will have the same effect when executed before any other related script tags.

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

Comments

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.