Permission Denied when working with web push notification in Laravel - javascript

I'm working with Webpush notification in Laravel. It shows permission denied when i click on send notification button, and i want to update the count as soon as i press that send notification button. I'm following this link : https://medium.com/#sagarmaheshwary31/push-notifications-with-laravel-and-webpush-446884265aaa
I'm using following code:
enable-push.js
'use strict';
const swReady = navigator.serviceWorker.ready;
document.addEventListener('DOMContentLoaded', function () {
initSW();
});
function initSW() {
if (!"serviceWorker" in navigator) {
//service worker isn't supported
return;
}
//don't use it here if you use service worker
//for other stuff.
if (!"PushManager" in window) {
//push isn't supported
return;
}
//register the service worker
navigator.serviceWorker.register('../sw.js')
.then(() => {
console.log('serviceWorker installed!')
initPush();
})
.catch((err) => {
console.log(err)
});
}
function initPush() {
if (!swReady) {
return;
}
new Promise(function (resolve, reject) {
const permissionResult = Notification.requestPermission(function (result) {
resolve(result);
});
if (permissionResult) {
permissionResult.then(resolve, reject);
}
})
.then((permissionResult) => {
console.log(permissionResult);
if (permissionResult !== 'granted') {
throw new Error('We weren\'t granted permission.');
}
subscribeUser();
});
}
/**
* Subscribe the user to push
*/
function subscribeUser() {
swReady
.then((registration) => {
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(
"BIHpWZJBO9Ilqq0UG4+zKmOcYFZBbYIf2cC/sNnEOeA9DCihcDCBhwSVO+ELV9UN/ktv0ksAgoOF53zFT+h9vh="
)
};
return registration.pushManager.subscribe(subscribeOptions);
})
.then((pushSubscription) => {
console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
storePushSubscription(pushSubscription);
});
}
/**
* send PushSubscription to server with AJAX.
* #param {object} pushSubscription
*/
function storePushSubscription(pushSubscription) {
const token = document.querySelector('meta[name=csrf-token]').getAttribute('content');
fetch('/push', {
method: 'POST',
body: JSON.stringify(pushSubscription),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': token
}
})
.then((res) => {
return res.json();
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
});
}
/**
* urlBase64ToUint8Array
*
* #param {string} base64String a public vapid key
*/
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
Please help to sort out my issue,

Related

Trying to Create localStorage Not Working (NextJS)

I need to pull inventory data to my NextJS app, I am then trying to store that data to localStorage, but it never gets set. What am I doing wrong?
if (process.browser && localStorage.getItem('inv') === undefined) {
const inv = await getInventory()
localStorage.setItem('inv', inv)
}
getInventory() is just a node script that pulls inventory data from a remote api and returns fullInventory.
Here is the code from getInventory():
const getInventory = async () => {
const token = await refreshToken()
const header = {
Authorization: `Bearer ${token}`,
};
const queries = await getQueriesCount();
axios.interceptors.response.use(function (response) {
return response;
}, async function (error) {
await new Promise(function (res) {
setTimeout(function () { res() }, 2000);
});
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshedHeader = await setHeader()
axios.defaults.headers = refreshedHeader
originalRequest.headers = refreshedHeader
return Promise.resolve(axios(originalRequest));
}
return Promise.reject(error);
});
let fullInventory = [];
for (let i = 0; i < queries; i++) {
setTimeout(async () => {
try {
const res = await axios({
url: `${MyApi}/Item.json&offset=${i * 100}&customSku=!~,`,
method: "get",
headers: header,
});
console.log(`adding items ${i * 100} through ${(i + 1) * 100}`);
const items = await res.data.Item;
items[0]
? (fullInventory = fullInventory.concat(items))
: fullInventory.push(items);
if (i + 1 === queries) {
return fullInventory;
}
} catch (error) {
console.error("We have a problem here: ", error.response);
}
}, 2000 * i);
};
}

Way to handle refresh token

I am working on login feature and have problem when refresh token.
When token expire making request to refresh token, remove the old token, and save the new token to AsyncStorage.
After login successfully have to function A and B. The function A is using the new token to make its request. the function B say that it need to refresh the token so make request to refresh token ( the request make successfully, token being refresh) but The token that request A is using now invalid - I think it happens due to asynchronous
This is my code that use to refresh token:
axiosInstance.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
if (error.response.status === CODE_TOKEN_EXPIRED) {
try {
const token = await authenticationService.getRefreshToken();
const response = await authenticationService.refreshToken(token);
await authenticationService.removeToken();
await authenticationService.storeToken(response.data.params.access_token);
await authenticationService.storeRefreshToken(response.data.params.refresh_token);
error.config.headers.Authorization = 'Bearer ' + response.data.params.access_token;
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.params.access_token;
return axiosInstance(error.config);
} catch (err) {
console.log(2, err);
await authenticationService.removeToken();
navigationService.navigate('LoginForm');
}
}
return Promise.reject(error);
}
);
Anyone know how to handle which asynchronous call for refresh token?
First would be for you to check if you are changing token to the correct axios instance. It is necessary to change Authorization header on error.response config as you did, but also for main axios instance (if you have one) like so: axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
If it is multiple parallel requests going on that could possibly need to be postponed after token is refreshed issue and answer gets complex, but check this gist with full refresh logic with axios.
I have implemented the same scenario in fetch API. you can also do this same in axios API. Try this to avoid interceptor concept.
Api.ts
export const api = ({ method, url, body, isProtected = true }) => {
return new Promise((resolve, reject) => {
const payload = {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
};
if (body !== null) {
(payload as any).body = JSON.stringify(body);
}
/**
* "isProtected" is used for API call without authToken
*/
if (isProtected) {
AsyncStorage.getItem(ACCESS_TOKEN).then(accessKey => {
(payload.headers as any).Authorization = `Bearer ${accessKey}`;
fetch(url, payload)
.then((response: any) => {
/*
* 419 status denotes the timeout of authToken
*/
if (response.status == 419) {
// refresh token
AsyncStorage.getItem(REFRESH_TOKEN).then(refreshKey => {
const payloadRef = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + refreshKey
}
};
/*
* This call refresh the authToken using refreshing call to renew the authToken
*/
fetch(URL.baseUrl + "/refresh", payloadRef)
.then((response: any) => response.json())
.then(response => {
/*
* if refresh token expired. redirect to login page
*/
if (response.status !== codes.SUCCESS) {
if (!User.sessionOver) {
User.sessionOver = true;
Alert.alert(
'Alert',
'Session Timeout',
[
{
text: 'Get back to Login',
onPress: () => {
// get to Login page
}
}
],
{ cancelable: false }
);
}
} else if (response.status == codes.SUCCESS) {
/*
* If refresh token got refreshed and set it as authToken and retry the api call.
*/
AsyncStorage.setItem(ACCESS_TOKEN, response.payload.access_key).then(() => {
(payload.headers as any).Authorization = 'Bearer ' + response.payload.access_key;
fetch(url, payload)
.then(response => response.json())
.then(response => {
if (response.status == codes.SUCCESS) {
resolve(response);
}
})
.catch(error => {
reject(error);
});
});
}
});
});
} else {
resolve(response.json());
}
})
.catch(error => {
reject(error);
});
});
} else {
fetch(url, payload)
.then((response: any) => {
response = response.json();
resolve(response);
})
.catch(error => {
reject(error);
});
}
});
};
MovieService.ts
import { api } from '../services/api';
import { URL } from '../config/UrlConfig';
const getMovies = () => {
const method = 'GET';
const url = URL.baseUrl + '/v1/top/movies';
const body = null;
const isProtected = true;
return api({ method, url, body, isProtected });
};
export { getMovies };
Maybe it will helps - https://gist.github.com/ModPhoenix/f1070f1696faeae52edf6ee616d0c1eb
import axios from "axios";
import { settings } from "../settings";
import { authAPI } from ".";
const request = axios.create({
baseURL: settings.apiV1,
});
request.interceptors.request.use(
(config) => {
// Get token and add it to header "Authorization"
const token = authAPI.getAccessToken();
if (token) {
config.headers.Authorization = token;
}
return config;
},
(error) => Promise.reject(error)
);
let loop = 0;
let isRefreshing = false;
let subscribers = [];
function subscribeTokenRefresh(cb) {
subscribers.push(cb);
}
function onRrefreshed(token) {
subscribers.map((cb) => cb(token));
}
request.interceptors.response.use(undefined, (err) => {
const {
config,
response: { status },
} = err;
const originalRequest = config;
if (status === 401 && loop < 1) {
loop++;
if (!isRefreshing) {
isRefreshing = true;
authAPI.refreshToken().then((respaonse) => {
const { data } = respaonse;
isRefreshing = false;
onRrefreshed(data.access_token);
authAPI.setAccessToken(data.access_token);
authAPI.setRefreshToken(data.refresh_token);
subscribers = [];
});
}
return new Promise((resolve) => {
subscribeTokenRefresh((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
resolve(axios(originalRequest));
});
});
}
return Promise.reject(err);
});
export default request;

How can I break this Javascript HTTP Infinite request loop after 3 requests?

So I've 2 components, Token.jsx and httpRequest.jsx.
Both of them call each other when the token expires and it goes into an infinite loop, I want to break the loop after 3 http erros.
export default function GenerateToken() {
return new Promise(((resolve) => {
const refreshToken = GetRefreshToken();
const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
const headers = {
'Content-Type': 'application/json',
};
const params = {
refreshToken,
};
httpRequest.makeHTTPCall('post', url, headers, params).then((tokenObject) => {
// Storing the idToken in localstorage
// reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
StoreIdToken(`Id ${tokenObject.id_token}`);
StoreUserId(tokenObject.user_id);
StoreRefreshToken(tokenObject.refresh_token);
resolve(tokenObject.id_token);
});
}));
}
// 2nd File
function makeHTTPCall(method, url, headers, params = null) {
return new Promise((resolve, reject) => {
headers.Authorization = GetIdToken();
headers['Content-Type'] = 'application/json';
qwest.setDefaultDataType('json');
qwest.setDefaultOptions({
headers,
});
// Make http request
qwest[`${method}`](url, params)
.then((xhr, response) => {
resolve(response);
})
.catch((error, xhr) => {
if (xhr.status === 401) { // IdToken expired
GenerateToken().then(() => {
resolve(GET(url));
});
}
else {
reject(error); // error
}
});
});
}
You can give both of them a parameter like tryCount, and increment it in one of the functions, rejecting once it reaches 2:
export default function GenerateToken(tryCount = 0) {
return new Promise((resolve) => {
const refreshToken = GetRefreshToken();
const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
const headers = {
'Content-Type': 'application/json',
};
const params = {
refreshToken,
};
httpRequest.makeHTTPCall('post', url, headers, params, tryCount).then((tokenObject) => {
// Storing the idToken in localstorage
// reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
StoreIdToken(`Id ${tokenObject.id_token}`);
StoreUserId(tokenObject.user_id);
StoreRefreshToken(tokenObject.refresh_token);
resolve(tokenObject.id_token);
});
});
}
// 2nd File
function makeHTTPCall(method, url, headers, params, tryCount) {
return new Promise((resolve, reject) => {
headers.Authorization = GetIdToken();
headers['Content-Type'] = 'application/json';
qwest.setDefaultDataType('json');
qwest.setDefaultOptions({
headers,
});
// Make http request
qwest[`${method}`](url, params)
.then((xhr, response) => {
resolve(response);
})
.catch((error, xhr) => {
if (xhr.status === 401 && tryCount <= 1) { // IdToken expired, and we've recursed less than twice so far
GenerateToken(tryCount + 1).then(() => {
resolve(GET(url));
});
} else {
reject(error); // error
}
});
});
}
Also note that you should avoid the explicit Promise construction antipattern:
export default function GenerateToken(tryCount = 0) {
const refreshToken = GetRefreshToken();
const url = `${cloudFunctionURL}/users/auth/idtoken/refresh`;
const headers = {
'Content-Type': 'application/json',
};
const params = {
refreshToken,
};
return httpRequest.makeHTTPCall('post', url, headers, params, tryCount).then((tokenObject) => {
// Storing the idToken in localstorage
// reactLocalStorage.set('PL_IdToken', tokenObject.idToken);
StoreIdToken(`Id ${tokenObject.id_token}`);
StoreUserId(tokenObject.user_id);
StoreRefreshToken(tokenObject.refresh_token);
return tokenObject.id_token;
});
}
// 2nd File
function makeHTTPCall(method, url, headers, params, tryCount) {
headers.Authorization = GetIdToken();
headers['Content-Type'] = 'application/json';
qwest.setDefaultDataType('json');
qwest.setDefaultOptions({
headers,
});
// Make http request
return qwest[`${method}`](url, params)
.then((xhr, response) => {
return response;
})
.catch((error, xhr) => {
if (xhr.status === 401 && tryCount <= 1) { // IdToken expired, and we've recursed less than twice so far
return GenerateToken(tryCount + 1).then(() => {
return GET(url);
});
} else {
throw new Error(error);
}
});
}

Possible Unhandled Promise Rejection (id: 0): Error missing baseUrl

I'm getting this error every time I press a specific button on my react-native app. I'm guessing it has to do something with an Api call or maybe it is trying to invoke URLs with localhost:8081, which may not be correct as it should be pointing to a server. I'm not sure exactly how to pinpoint the problem. Any help would be much appreciated. I'm also now sure if the problem is coming from the file I shared underneath.
App Warning message:
This is my RestClient code:
import {Alert, AsyncStorage} from 'react-native'
import {resetRouteTo} from 'util/NavigationHelper'
import {store} from '../index.js'
import {dropdownAlert} from 'util/AlertManager'
const DEFAULT_ERROR = {error: {code: 500, message: 'No JSON message'}}
export default class RestClient {
constructor (baseUrl = '', navigation, { headers = {}, devMode = false, simulatedDelay = 0 } = {}) {
if (!baseUrl) throw new Error('missing baseUrl')
this.navigation = navigation
this.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
Object.assign(this.headers, headers)
this.baseUrl = baseUrl
this.simulatedDelay = simulatedDelay
this.devMode = devMode
}
_clearTokenAndGo () {
AsyncStorage.removeItem('apiToken')
Alert.alert(
'Error',
'Something went wrong and your account needs to be re-instantiated.',
[
{text: 'OK', onPress: () => resetRouteTo(this.navigation, 'OnboardingFirst')}
],
{ cancelable: false }
)
}
_simulateDelay () {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, this.simulatedDelay)
})
}
async _parseIfJson (response) {
var contentType = response.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json()
}
return null
}
async _handleError (response) {
const body = await this._parseIfJson(response)
if (!body) {
dropdownAlert('error', `Server Error ${response.status}`, 'Something went wrong on the server')
return DEFAULT_ERROR
}
switch (response.status) {
case 200: {
break
}
case 401: {
if (body.error === 'Unauthenticated.') {
this._clearTokenAndGo()
}
break
}
case 400: {
dropdownAlert('error', `Error ${body.error.code}`, body.error.message)
break
}
default: {
if (body.error) {
dropdownAlert('error', `Error ${body.error.code}`, body.error.message)
} else {
dropdownAlert('error', 'Error', `An unknown error has occurred. Http status ${response.status}`)
}
break
}
}
return body
}
_fullRoute (url) {
return `${this.baseUrl}${url}`
}
async _fetch (route, method, body, isQuery = false) {
if (!route) throw new Error('Route is undefined')
if (!store.getState().netinfo.isConnected) {
this.navigation.navigate('BlockScreen')
return {success: false, error: {code: 1, message: 'No internet connection.'}}
}
var fullRoute = this._fullRoute(route)
if (isQuery && body) {
var qs = require('qs')
const query = qs.stringify(body)
fullRoute = `${fullRoute}?${query}`
body = undefined
}
let opts = {
method,
headers: this.headers
}
if (body) {
Object.assign(opts, { body: JSON.stringify(body) })
}
const fetchPromise = () => fetch(fullRoute, opts)
if (this.devMode && this.simulatedDelay > 0) {
// Simulate an n-second delay in every request
return this._simulateDelay()
.then(() => fetchPromise())
.then(response => response.json())
} else {
let promise = await fetch(fullRoute, opts)
console.log('Logging response =>')
console.log(promise)
return this._handleError(promise)
}
}
GET (route, query) { return this._fetch(route, 'GET', query, true) }
POST (route, body) { return this._fetch(route, 'POST', body) }
PUT (route, body) { return this._fetch(route, 'PUT', body) }
DELETE (route, query) { return this._fetch(route, 'DELETE', query, true) }
}
Other files using RestClient:
import RestClient from 'util/RestClientLib'
import qs from 'qs'
import { Linking, AsyncStorage } from 'react-native'
import Config from 'react-native-config'
var SHA256 = require('crypto-js/sha256')
export default class ApiClient extends RestClient {
constructor (authToken, navigation) {
console.log('constructing apiClient with base: ', Config.API_URL)
super(Config.API_URL, navigation, {
headers: {
'Authorization': 'Bearer ' + authToken
}
})
}
_switchSchemeTo (url, scheme) {
var split = url.split(':')
split[0] = scheme
return split.join(':')
}
_makeAppUrl (url) {
const prefix = url.split('.')[0]
const bank = prefix.substr(prefix.lastIndexOf('/') + 1, prefix.length)
switch (bank) {
case 'florijnbank':
return this._switchSchemeTo(url, 'flrb')
default:
return url
}
}
async _openUrl (url) {
const openInApp = await AsyncStorage.getItem('openInApp')
const appUrl = this._makeAppUrl(url)
Linking.canOpenURL(appUrl).then(supported => {
if (!supported || openInApp !== 'true') {
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log('Can\'t handle url: ' + url)
} else {
Linking.openURL(url)
}
}).catch(err => console.error('An error occurred', err))
} else {
Linking.openURL(appUrl)
}
}).catch(err => console.error('An error occurred', err))
}
async createToken (pin) {
var hash = SHA256(pin).toString()
const query = {pincode: hash}
let response = await this.POST('/user', query)
return response.api_token
}
async checkPin (pin) {
const hash = SHA256(pin).toString()
const query = {pincode: hash}
return this.GET('/user/validate', query)
}
getAccounts () {
return this.GET('/account')
}
getBalance (iban) {
return this.GET(`/account/${iban}`)
}
async getPermissionBank (bank) {
const query = {
bank_id: bank
}
let response = await this.POST('/account', query)
return this._openUrl(response.url)
}
postCredentialsAis (form) {
return this.POST('/account/password', form)
}
async ais (iban) {
let response = await this.GET(`/ais/${iban}`)
if (response.url == null) {
return true
}
this._openUrl(response.url)
return false
}
getTransactionDetails (requestId) {
return this.GET(`/request/${requestId}`)
}
getTransactions (iban) {
return this.GET(`/account/${iban}/transaction`)
}
getContacts () {
return this.GET('/contacts')
}
getSettings () {
return this.GET('/startup')
}
deleteAccount (iban) {
return this.DELETE(`/account/${iban}`)
}
/**
* async submitTransfer - submits a transfer
*
* #param {Object} options object which holds the pin, iban, sso and query
* #param {Object} transfer hold the transfer information
* #return {Boolean} either opens a link or a boolean for success
*/
submitTransfer (iban, credentials, transfer) {
const url = `/account/${iban}/transaction?${qs.stringify(credentials)}`
const body = {
counter_iban: transfer.counterIban,
counter_account_name: transfer.name,
amount: transfer.amount,
description: transfer.description,
reference: transfer.reference
}
return this.POST(url, body)
}
qrConfirmTransfer (transactionId, iban, credentials) {
const url = `/request/${transactionId}/confirm/${iban}?${qs.stringify(credentials)}`
return this.POST(url)
}
directConfirmTransfer (transactionId, iban, form) {
const url = `/account/${iban}/transaction/${transactionId}`
return this.POST(url, form)
}
verificationRequired (iban, amount) {
const query = {amount: amount}
return this.GET(`/veriReq/${iban}`, query)
}
};

Web push notifications click doesn't work

I'm trying to do web push notifications that are clickable and when user click on it he should be redirected to some url.
I'm using Laravel 5.4 with package:
https://github.com/laravel-notification-channels/webpush
Here is some of the code:
app.blade.php
<script>
var _registration = null;
function registerServiceWorker() {
return navigator.serviceWorker.register('{{ asset('assets/js/service-worker.js') }}')
.then(function(registration) {
console.log('Service worker successfully registered.');
_registration = registration;
return registration;
})
.catch(function(err) {
console.error('Unable to register service worker.', err);
});
}
function askPermission() {
return new Promise(function(resolve, reject) {
const permissionResult = Notification.requestPermission(function(result) {
resolve(result);
});
if (permissionResult) {
permissionResult.then(resolve, reject);
}
})
.then(function(permissionResult) {
if (permissionResult !== 'granted') {
throw new Error('We weren\'t granted permission.');
}
else{
subscribeUserToPush();
}
});
}
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function getSWRegistration(){
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (_registration != null) {
resolve(_registration);
}
else {
reject(Error("It broke"));
}
});
return promise;
}
function subscribeUserToPush() {
getSWRegistration()
.then(function(registration) {
console.log(registration);
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(
"{{env('VAPID_PUBLIC_KEY')}}"
)
};
return registration.pushManager.subscribe(subscribeOptions);
})
.then(function(pushSubscription) {
console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
sendSubscriptionToBackEnd(pushSubscription);
return pushSubscription;
});
}
function sendSubscriptionToBackEnd(subscription) {
return fetch('/api/save-subscription/{{Auth::user()->id}}', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(subscription)
})
.then(function(response) {
if (!response.ok) {
throw new Error('Bad status code from server.');
}
return response.json();
})
.then(function(responseData) {
if (!(responseData.data && responseData.data.success)) {
throw new Error('Bad response from server.');
}
});
}
function enableNotifications(){
//register service worker
//check permission for notification/ask
askPermission();
}
registerServiceWorker();
</script>
service-worker.js
self.addEventListener('push', function(event) {
if (event.data) {
var data = event.data.json();
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon
});
console.log('This push event has data: ', event.data.text());
} else {
console.log('This push event has no data.');
}
});
self.addEventListener('notificationclick', function(event) {
console.log('Notification click: tag ', event.notification.tag);
event.notification.close();
var url = 'https://google.com';
console.log('kliknieto');
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(windowClients) {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
Notification:
public function toWebPush($notifiable, $notification)
{
return (new WebPushMessage)
->title('Some title')
->icon(asset("img/img.jpg"))
->body('Some body')
->action('View action', 'view_action')
->data(['id' => $notification->id, 'link' => $this->link]);
}
Generally it display the notification, but when I am trying to click on it I want to be redirected to https://google.com, but nothing happens. Do you have any idea how to fix it?
The problem has been solved after reset Google Chrome settings to default.
Found the solution. The action method accepts title and action, but the action is not an url. You should add notificationclick event to your service-worker.js file.
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(
self.clients.openWindow('https://www.example.com/')
);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/notificationclick_event

Categories