【发布时间】:2021-12-29 07:54:35
【问题描述】:
我可以在 laravel 和 React 中创建通知。我已按照教程进行操作,但我不知道如何将通知从 laravel 发送到我的反应应用程序。这是我在 Laravel 控制器中得到的代码。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Feature\HttpHandler;
use App\Notifications\PushDemo;
use App\Models\Users;
use Illuminate\Support\Facades\Auth;
use Notification;
use Illuminate\Support\Facades\Log;
use NotificationChannels\WebPush\PushSubscription;
use Illuminate\Support\Facades\Http;
use App\Feature\ApiResponse;
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;
}
}
商店功能有效。 作为反应,我在我的 service-worker.js 中有这段代码来监听事件。 (这是需要工作的一段代码,但它表示意外使用 'self' no restricted-globals)
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));
}
})
})
}
这个函数调用有效。只是似乎从未调用过服务工作者函数,并且它不会将通知发送到我的反应应用程序。我该如何解决?
【问题讨论】:
-
对于实时通知,我推荐 laravel-websocket 它是免费和开源的,您可以为通知和调度创建一个新事件,laravel echo 将在前端捕获
标签: php reactjs laravel function api