问题
I've coded a web app in Laravel (PHP). Let's call it example.com.
I'd like (as an admin) to have a button that toggles in real-time the visibility of an element example.com.
That is, public visitors who are looking at example.com could see the effect of the button that I pressed even if they never refresh the page.
It seems that this would be possible via something like Pusher and https://laravel.com/docs/6.x/broadcasting (or WebSocket or WebRTC?).
The JS in the client would have:
Echo.private('specialToggle').listen('ToggleEnabled', (e) => {
console.log(e.something);
$('#myElement').show();
});
What I don't understand is why Laravel can't manage its own WebSocket connections and instead needs to use Pusher Channels. If a third party such as Pusher is already necessary, why is there any server-side code required at all?
For example, Tawk.to is a free live chat widget, and on their website, I can flip a switch that instantly toggles whether the chat widget on my example.com appears or disappears for any visitors who are currently viewing example.com, even if they don't refresh the page. There was no server-side code on example.com to make this happen.
For a case as simple as what I'm wanting to do now, could I similarly skip server-side Laravel Broadcast setup and instead communicate with Pusher (or an equivalent) only via JavaScript? I.e. When I'm logged into my site as an admin, I'd have access to certain pages where JavaScript functions would be able to send instructions to Pusher. Public visitors viewing example.com would see the effects of those actions instantly because of the JavaScript loaded in their browser.
Am I on the right track?
来源:https://stackoverflow.com/questions/59384778/updating-client-side-js-application-in-real-time-based-on-admin-activity-in-js