Search code examples
javascriptbuttonpush-notificationaction

Notification JavaScript not displaying Actions buttons


Here is my JavaScript Code.

'use strict';
/*
import {
    pkg
} from './module/';
*/

function push() {
    try {
        let p, q, y = '';
        const ng = navigator,
            j = x => {
                return JSON.parse(x)
            },
            v = './push/api/v1',
            o = x => !window.su ? alert(x) : fetch(v, {
                method: 'POST',
                headers: {
                    body: JSON.stringify({
                        a: su,
                        b: x
                    })
                }
            }),
            e = new EventSource(v);
        e.onmessage = m => {
            p = j(m.data);
            Notification.requestPermission().then(n => ng.serviceWorker.register('sw.js').then(w => {
                (p.a).forEach(b => y += {
                    "action": `"${b}"`,
                    "title": `"${b}"`
                }, );
                let arg = {
                    body: p.y,
                    icon: p.z,
                    badge: p.z,
                    actions: [y]
                };
                w.showNotification(p.x, arg);
                o(1);
                y = ''
            }))
        }
    } catch (e0) {
        alert(e0)
    }
}
<button onclick="push()">Push</button>
<span id="io">Demo...</span>
<script src="main.js"></script>

And Here is my PHP code

<?php
header("X-Accel-Buffering: no");
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
while (1) {
echo 'data: {"x":"Demo notification","y":"Hence no further actions needed. Thanks for cooperation.","z":"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Apple_logo_grey.svg/1724px-Apple_logo_grey.svg.png","a":["Archive","Demo Btn"]}'."\n\n";
sleep(10);
flush();
}
?>

I'm expecting that the elements of array as stated in PHP code to be displayed as a button in the JavaScript notification. I'm 99.9% sure that the issue is with JSON handling. But can't figure out the issue. If I entirely remove the actions property in arguments of Notification API, it's working perfectly.

If I completely remove actions property, then I'm getting notification. Here is the sample output. Notification permission Displyaing notification

Similar to 'Site Settings' option in notification, I want the elements of the array as stated in PHP code in JSON element 'a' to be displayed as buttons.


Solution

  • The actions property in notifications accepts an array of objects, but here you are passing it as array of string. You can simply create an array and pass the actions in it

    let y = []
    
    (p.a).forEach(b => y.push({
      "action": `${b}`,
      "title": `${b}`
    }));
    let arg = {
      body: p.y,
      icon: p.z,
      badge: p.z,
      actions: y
    };