JavaScript cannot be injected via Laravel Livewire events.

Video thumbnail

Livewire doesn't allow JavaScript to be executed from events like wire:click, wire:change, etc.; this is for security reasons, meaning that once the page is loaded, the browser doesn't allow it.

Clear example:

<div class="mt-5">
@if ($buy)
   <h1>HELLO!!!!</h1>
   <script>
      alert()
   </script> 
@else
****
<button class="btn btn-success mb-3" wire:click="readyBuy">
      {{ __('Buy') }}
</button>

For example, if we change the value of $buy using a Livewire event:

function readyBuy()
{
    $this->buy = true;
}

This DOESN'T work; the alert is ignored by the browser, as mentioned above. What you need to do is always load the JS and use a Livewire event:

function readyBuy()
{
    $this->buy = true;
}

But if I try to insert that script from a Livewire event, such as when clicking a button, it doesn't work. The browser doesn't execute it for security reasons.

Why can't JS be injected from events?
Modern browsers block dynamic JavaScript injection for security reasons. While you can "fool" it using the browser console, it's not the same as injecting it from an event within the browser's render cycle. The browser blocks it because it could be used to inject malicious scripts.

That we run from the server:

function readyBuy()
{
    $this->buy = true;

    + $this->dispatch('load-payments', [
    +    'price' => $this->price,
    + ]);
}

And we define in the client:

<script>
Livewire.on('load-payments', async (data) => {
   alert()
})
</script> 

I agree to receive announcements of interest about this Blog.

We talked about an important LACK of Laravel Livewire and the use of events, you CANNOT inject JS.

| 👤 Andrés Cruz

🇪🇸 En español