0

I'm trying to take a PHP constant (N_BELL) and apply it to JavaScript.

There is a bell on the page. If clicked, a bubble appears. Inside the bubble there may be pretty much anything: just text, html, or a script.

If just a text is assigned to the constant, everything is Ok. Like N_BELL = 'test'.

But if a script, then eveything blows up.

For example, I'd like to insert this script:

<script src="//web.webformscr.com/apps/fc3/build/loader.js" async sp-form-id="bf1c5b05db76f8d703e531a06f371e6ffd7cb9cbba72fa9fc5d97321a710dc04"></script>

This script will render an email subscription form.

php:

$n_bell_script = '<script>
var bells_with_message = document.querySelectorAll(".n-bell-with-message");
var bubble_shown = false;

function remove_message_from_bell(item) {       
    item.classList.add("n-bell-hidden");
    item.parentElement.querySelector(".n-bell-without-message").classList.remove("n-bell-hidden");
}   

function display_bubble(item){      
    item.parentElement.querySelector(".n-bell-bubble").classList.remove("n-bell-hidden");
    item.parentElement.querySelector(".n-bell-bubble").innerHTML = \'' .  N_BELL . '\';
    bubble_shown = true;
}

bells_with_message.forEach(item => {
    item.addEventListener(\'click\', event => {
        remove_message_from_bell(item);
        display_bubble(item);
    });
  });
</script>';

Resulting html:

<script>
    var bells_with_message = document.querySelectorAll(".n-bell-with-message");
    var bubble_shown = false;

    function remove_message_from_bell(item) {       
        item.classList.add("n-bell-hidden");
        item.parentElement.querySelector(".n-bell-without-message").classList.remove("n-bell-hidden");
    }   

    function display_bubble(item){      
        item.parentElement.querySelector(".n-bell-bubble").classList.remove("n-bell-hidden");
        item.parentElement.querySelector(".n-bell-bubble").innerHTML = '<script src="//web.webformscr.com/apps/fc3/build/loader.js" async sp-form-id="bf1c5b05db76f8d703e531a06f371e6ffd7cb9cbba72fa9fc5d97321a710dc04"></script>';
        bubble_shown = true;
    }

    bells_with_message.forEach(item => {
        item.addEventListener('click', event => {
            remove_message_from_bell(item);
            display_bubble(item);
        });
      });
    </script>

w3org validator finds errors:

enter image description here

enter image description here

The question is not about PHP. It is about JS. Could you tell me how JS should look like for the code not blow up? Maybe something to escape or the like?

enter image description here enter image description here

Kifsif
  • 3,127
  • 10
  • 33
  • 41

0 Answers0