Laravel和反应,如何从Laravel向我的反应应用程序发出通知(意外使用"self"没有限制全局错误)



我可以在laravel和React中创建通知。我已经学习了教程,但我不知道如何将通知从laravel发送到我的react应用程序。这是我在Laravel控制器中得到的代码。

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppFeatureHttpHandler;
use AppNotificationsPushDemo;
use AppModelsUsers;
use IlluminateSupportFacadesAuth;
use Notification;
use IlluminateSupportFacadesLog;
use NotificationChannelsWebPushPushSubscription;
use IlluminateSupportFacadesHttp;
use AppFeatureApiResponse;

class PushController extends Controller
{
use ApiResponse;
use HttpHandler;
public function __construct(){
}
public function push(){
Log::info('Push push function  called');
$users = Users::all();
Notification::send($users,new PushDemo);
return redirect()->back();
}
public function store(Request $request)
{
Log::info('Push store called');
// get user from request
//$user = Users::findOrFail($request->userId);

$user = Users::whereUrl($request->post('URL'))->firstOrFail();
$b = $request['body'];
// create PushSubscription and connect to this user
$pushsub = $user->updatePushSubscription($request->body['endpoint'], $request->body['keys']['p256dh'], $request->body['keys']['auth']);
Log::info('WORKED');
return $pushsub;
}

}

商店功能正常。在react中,我在service-worker.js中有一段代码用于侦听事件。(这是一段需要工作的代码,但它说"self"的意外使用没有限制全局(

self.addEventListener('push', function (e) {
console.log('push');
if (!(self.Notification && self.Notification.permission === 'granted')) {
//notifications aren't supported or permission not granted!
return;
}
if (e.data) {
var msg = e.data.json();
console.log(msg)
e.waitUntil(self.registration.showNotification(msg.title, {
body: msg.body,
icon: msg.icon,
actions: msg.actions
}));
}
});

这个代码从来没有被调用过,但它应该在我点击这个按钮时被调用:

<button onClick={() => test()}>
test notification
</button>

这是通过Laravel应用程序的功能:

function test(){
console.log('test');
workerApi.makePushNotification({ URL, token})
.then(response => {
if (response.hasOwnProperty('message') && response.hasOwnProperty('type')) {
}
else {
console.log(JSON.stringify(response.data));

}
})
})
}

此函数调用有效。只是它看起来像从未调用过serviceworker函数,也没有向我的react应用程序发送通知。我该如何解决此问题?

嘿,你应该为监听器实时事件使用一些实时库,比如pusher,然后你可以将消息从服务器发送到前端

要在laravel应用程序上安装推进器,请查看本文https://www.codecheef.org/article/real-time-event-broadcasting-with-laravel-6-and-pusher

以及您的react应用

npm安装--保存推送器js

您的组件文件

import Pusher from 'pusher-js';
useEffect(() => {
var pusher = new Pusher("your-pusher-key", {
cluster: "ap2",
encrypted: true,
});
var channel = pusher.subscribe("notifyChannel");
channel.bind("notifyChannel", async function (response) {
alert('some notification');
})
});

最新更新