I'm trying to add a Qualtrics survey pop-up on a specific page in a Lightning community. Adding the JavaScript <script> to the community <head> runs it on every page, so I created a Lightning component especially for it. I'm trying to dynamically inject the into the head on doInit.

    doInit : function(component, event, helper) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';

        var inlineScript = document.createTextNode('alert("hello world");');

Here I've replaced the full inline JavaScript snippet from Qualtrics with alert("hello world"). I've added the Lightning component to the page, but the JavaScript isn't executing. I know you can't add <script> inside the component markup. Is it allowed in the Controller.js?


Have you tried to use ltng:require? Or lightning:container. It depends on what Qualtrics JS snippets should do.

Anyway, you can create VisualForce page(Use Visualforce in Lightning Communities), which can have injected java script.

| improve this answer | |
  • I tried <ltng:require scripts /> but that rendered <script data-locker-src="resource/javascript/qualtrics.js"> and it didn't execute. Not sure why data-locker-src was appended to it. – Matt Smith Jul 19 '19 at 0:16
  • Why? Because Locker Service blocks script injection of this sort. – Charles T Jul 19 '19 at 0:29
  • So even using <ltng:require /> in the Lightning Component pointing to a JS file in Static Resources will be blocked by Locker Service? – Matt Smith Jul 19 '19 at 1:00

I would think that the moment you put this in a Lightning component, it gets subjected to Lightning Locker Service which bars inline scripts of this sort. I suppose you could try making it a pre-Locker API version like v39.

Alternatively you could possibly do something like... raise a DOM event from the Lightning component indicating that this is a page on which you want the script to fire. In the header script you have an event listener that, on receiving the DOM event, injects the script.

Or have the header script only run if the URL matches some pattern.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.