2017-07-31 45 views
-1

目前我能夠發送「你好」作爲通知。現在我想發送一個文本框的值作爲notification.below是我正在使用的代碼。我需要做什麼改變?如何將文本框的值作爲網頁推送通知發送?

這裏是我的index.html:

<html> 
    <body> 
     <h1>Web Push Notification</h1> 
     <button id="push-subscription-button">Push notifications ! 
     </button><br><br> 
     <input name="message" id="message" value="" 
     placeholder="Message"/><br><br> 

    <button id="send-Push-Button">Send Push notifications</button> 

    <script type="text/javascript" src="app.js"></script> 
    </body> 
    </html> 


    Here is send_push_notification.php: 

    <?php 
    require __DIR__ . '/../vendor/autoload.php'; 
    use Minishlink\WebPush\WebPush; 


    $subscription = json_decode(file_get_contents('php://input'), 
    true); 

$auth = array(
'VAPID' => array(

    'subject' => '', 
    'publicKey' => '', 
    'privateKey' => ' ' 
    ), 
); 

    $webPush = new WebPush($auth); 

    $res = $webPush->sendNotification(
    $subscription['endpoint'], 
    "Hello", 
    $subscription['key'], 
    $subscription['token'], 
    true 
    ); 

    app.js: 

    document.addEventListener("DOMContentLoaded",() => { 
    const applicationServerKey = "`enter code here`"; 
    let isPushEnabled = false; 

    const pushButton = document.querySelector('#push-subscription- 
    button'); 
    if (!pushButton) { 
    return; 
    } 

pushButton.addEventListener('click', function() { 
    if (isPushEnabled) { 
     push_unsubscribe(); 
    } else { 
     push_subscribe(); 
    } 
    }); 

    if (!('serviceWorker' in navigator)) { 
    console.warn("Service workers are not supported by this browser"); 
    changePushButtonState('incompatible'); 
    return; 
    } 

    if (!('PushManager' in window)) { 
    console.warn('Push notifications are not supported by this 
    browser'); 
    changePushButtonState('incompatible'); 
    return; 
    } 

    if (!('showNotification' in ServiceWorkerRegistration.prototype)) 
    { 
    console.warn('Notifications are not supported by this browser'); 
    changePushButtonState('incompatible'); 
    return; 
    } 


    if (Notification.permission === 'denied') { 
    console.warn('Notifications are denied by the user'); 
    changePushButtonState('incompatible'); 
    return; 
    } 

     navigator.serviceWorker.register("serviceWorker.js") 
     .then(() => { 
     console.log('[SW] Service worker has been registered'); 
     push_updateSubscription(); 
    }, e => { 
     console.error('[SW] Service worker registration failed', e); 
     changePushButtonState('incompatible'); 
    }); 

    function changePushButtonState (state) { 
    switch (state) { 
     case 'enabled': 
      pushButton.disabled = false; 
      pushButton.textContent = "Disable Push notifications"; 
      isPushEnabled = true; 
      break; 
     case 'disabled': 
      pushButton.disabled = false; 
      pushButton.textContent = "Enable Push notifications"; 
      isPushEnabled = false; 
      break; 
     case 'computing': 
      pushButton.disabled = true; 
      pushButton.textContent = "Loading..."; 
      break; 
     case 'incompatible': 
      pushButton.disabled = true; 
      pushButton.textContent = "Push notifications are not 
     compatible with this browser"; 
      break; 
     default: 
      console.error('Unhandled push button state', state); 
      break; 
     } 
    } 

    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 push_subscribe() { 
    changePushButtonState('computing'); 

    navigator.serviceWorker.ready 
    .then(serviceWorkerRegistration => 
    serviceWorkerRegistration.pushManager.subscribe({ 
     userVisibleOnly: true, 
     applicationServerKey: 
     urlBase64ToUint8Array(applicationServerKey), 
    })) 
    .then(subscription => { 
     // Subscription was successful 
     // create subscription on your server 
     return push_sendSubscriptionToServer(subscription, 'POST'); 
     }) 
     .then(subscription => subscription && 
     changePushButtonState('enabled')) // update your UI 
     .catch(e => { 
     if (Notification.permission === 'denied') { 
      // The user denied the notification permission which 
      // means we failed to subscribe and the user will need 
      // to manually change the notification permission to 
      // subscribe to push messages 
      console.warn('Notifications are denied by the user.'); 
      changePushButtonState('incompatible'); 
     } else { 

      console.error('Impossible to subscribe to push 
      notifications', e); 
       changePushButtonState('disabled'); 
     } 
     }); 
    } 

     function push_updateSubscription() { 
     navigator.serviceWorker.ready.then(serviceWorkerRegistration 
     => serviceWorkerRegistration.pushManager.getSubscription()) 
     .then(subscription => { 
     changePushButtonState('disabled'); 

     if (!subscription) { 

      return; 
     } 


     return push_sendSubscriptionToServer(subscription, 'PUT'); 
    }) 
    .then(subscription => subscription && 
    changePushButtonState('enabled')) 
    .catch(e => { 
     console.error('Error when updating the subscription', e); 
    }); 
    } 

    function push_unsubscribe() { 
    changePushButtonState('computing'); 


    navigator.serviceWorker.ready 
    .then(serviceWorkerRegistration => 
    serviceWorkerRegistration.pushManager.getSubscription()) 
    .then(subscription => { 

     if (!subscription) { 
      // No subscription object, so set the state 
      // to allow the user to subscribe to push 
      changePushButtonState('disabled'); 
      return; 
     } 

     // We have a subscription, unsubscribe 
     // Remove push subscription from server 
     return push_sendSubscriptionToServer(subscription, 'DELETE'); 
    }) 
    .then(subscription => subscription.unsubscribe()) 
    .then(() => changePushButtonState('disabled')) 
    .catch(e => { 

     console.error('Error when unsubscribing the user', e); 
     changePushButtonState('disabled'); 
    }); 
    } 

function push_sendSubscriptionToServer(subscription, method) { 
    const key = subscription.getKey('p256dh'); 
    const token = subscription.getKey('auth'); 

    return fetch('push_subscription.php', { 
     method, 
     body: JSON.stringify({ 
      endpoint: subscription.endpoint, 
      key: key ? btoa(String.fromCharCode.apply(null, new 
      Uint8Array(key))) : null, 
      token: token ? btoa(String.fromCharCode.apply(null, new 
      Uint8Array(token))) : null 
     }), 
     }).then(() => subscription); 
     } 



     const sendPushButton = document.querySelector('#send-push- 
     button'); 
     if (!sendPushButton) { 
     return; 
     } 

     sendPushButton.addEventListener('click',() => 
    navigator.serviceWorker.ready 
    .then(serviceWorkerRegistration => 
    serviceWorkerRegistration.pushManager.getSubscription()) 
    .then(subscription => { 

     if (!subscription) { 

    alert('Please enable push notifications'); 
      return; 
     } 

     var msg= document.getElementById("message").value; 
    // alert(msg); 

     const key = subscription.getKey('p256dh'); 
     const token = subscription.getKey('auth'); 

     fetch('send_push_notification.php', { 

      method: 'POST', 
      body: JSON.stringify({ 

       endpoint:subscription.endpoint, 
       key: key ? btoa(String.fromCharCode.apply(null, new 
       Uint8Array(subscription.getKey('p256dh')))) : null, 
       token: token ? btoa(String.fromCharCode.apply(null, 
       new Uint8Array(subscription.getKey('auth')))) : null, 
      }) 
     }) 
     }) 
    ); 
    }); 

我應該從哪裏獲取文本框的值,併發送推-notification.php用「你好」更換呢?

+1

該腳本看起來相當複雜。你能詳細解釋它的功能嗎? –

+0

關注[這些](https://meta.stackoverflow.com/a/291370/1783163)簡單的規則可以改善您的問題。我建議跟着他們。我現在部分解決了你的問題,但我不能每次都和你在一起:-)(尤其是,在你的情況下:「我」總是用英文大寫!) – peterh

+0

你好......我對上面的代碼做了一些修改,它按照要求工作,但它在本地工作,而不是在上傳到server.please時告訴問題是什麼。 – Nisha

回答