使用 PHP 的 HTML5 通知 [英] HTML5 Notification With PHP

查看:31
本文介绍了使用 PHP 的 HTML5 通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Facebook 开始在桌面上使用 HTML5 通知,我想我会开始涉足它来为我的博客带来乐趣.我的想法很简单:新博客出来了,apache cronjob 每 X 分钟运行一次并调用一个文件,执行一些 PHP 魔法,然后发出通知.

I noticed Facebook started using the HTML5 notification for desktop and I thought I would start dabbling in it for fun for my blog. My idea is pretty simple: new blog comes out, apache cronjob runs every X minutes and calls a file, does some PHP wizardry and out goes the notification.

我在网上查看并找到了使用 node.js 和 angular 的示例,但我不习惯使用其中任何一个,所以我宁愿坚持使用 PHP.

I have looked online and found examples using node.js and angular, but I'm not comfortable using either of those so I'd rather stick with PHP.

这是我的流程:用户访问我的博客并单击一个按钮以允许通知.为简洁起见,以下代码在用户单击通知"按钮时向用户发送通知.这非常有效,理论上应该让他们订阅任何未来的通知.

Here is my process: The user goes to my blog and will click a button to allow notifications. For brevity, the below code sends the users a notification when they click the "notify" button. This works perfectly, and in theory should subscribe them to any future notifications.

if ('Notification' in window) {

function notifyUser() {
    var title = 'example title';
    var options = {
        body: 'example body',
        icon: 'example icon'
    };

    if (Notification.permission === "granted") {
        var notification = new Notification(title, options);
    } else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
            if (permission === "granted") {
                var notification = new Notification(title, options);
            }
        });
    }

}

$('#notify').click(function() {
    notifyUser();
    return false;
});

} else {
    //not happening
}

你可以看到上面的fiddle.

授予用户访问权限,现在我应该可以随时向他们发送通知.惊人的!然后我写了一个博客条目,它的 ID 是 XYZ.我的 cronjob 运行并调用以下 PHP 脚本,使用上面的 node.js 示例作为模板.

Access to the user is granted and now I should be able to send them notifications whenever I want. Awesome! I then write up a blog entry and it has the ID of XYZ. My cronjob goes and calls the following PHP script, using the above node.js example as a template.

(在这个例子中,我只是从我的手机手动调用脚本并观看我的桌面屏幕.由于我的桌面订阅"到了同一个域,我认为以下将/应该工作.)

(In this example I am just calling the script manually from my phone and watching my desktop screen. Since my desktop is "subscribed" to the same domain, I think the following would/should work.)

$num = $_GET['num'];

$db = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if($db) {
    mysql_select_db('mydb', $db);
    $select = "SELECT alert FROM blog WHERE id = ".$num." && alert = 0 LIMIT 1";
    $results = mysql_query($select) or die(mysql_error());
    $output = '';
    while($row = mysql_fetch_object($results)) { 

        $output .= "<script>

        var title = 'new blog!';
        var options = {
            body: 'come read my new blog!',
            icon: 'same icon as before or maybe a new one!'
        };

        var notification = new Notification(title, options);

        </script>";

      $update = "UPDATE blog SET alert = 1 WHERE id = ".$num." && alert = 0 LIMIT 1";
      mysql_query($update) or die(mysql_error());

    }

    echo $output;

}

然后我检查了数据库和博客条目 XYZ 的警报"现在设置为1",但我的桌面浏览器从未收到通知.由于我的浏览器订阅了与推送通知相同的 URL,我想我会收到一条消息.

I then check the database and blog entry XYZ's "alert" is now set to "1", yet my desktop browser never got notified. Since my browser is subscribed to the same URL that is pushing out the notification, I would imagine I'd get a message.

要么是我做错了什么(也许 PHP 不是正确的语言?),要么是我误解了规范.有人可以帮我指出正确的方向吗?我想我错过了一些东西.

Either I'm doing something wrong (perhaps PHP isn't the right language for this?), or I'm misunderstanding the spec. Could somebody help point me in the right direction? I think I'm missing something.

非常感谢.

更新 1

根据评论,如果我只是在其中调用一个脚本:

According to the comments, if I just call a script with this in it:

 var title = 'new blog!';
 var options = {
    body: 'come read my new blog!',
    icon: 'same icon as before or maybe a new one!'
 };

  var notification = new Notification(title, options);

它应该会影响订阅我的通知的所有设备.我在手机上试过这个,但我的桌面仍然没有收到通知.我仍然认为我错过了一些东西,因为我的通知似乎卡在一台设备上,只能在页面加载或点击时调用,而不是 Facebook,即使页面未在浏览器中打开,它也会向您发送通知.

It should hit all devices that are subscribed to my notifications. I tried this on my phone but my desktop still didn't get a notification. I still think I'm missing something as my notifications seem stuck to one device and can only be called on page-load or on click as opposed to Facebook which sends you notifications even if the page isn't open in your browser.

推荐答案

您的问题是缺少 AJAX 来连接 Javascript 和 PHP.PHP 脚本的工作方式是手动运行脚本,因此只有点击该脚本的设备才会看到通知.目前没有任何东西可以将该信息实际发送到您的其他设备.

Your problem is the lack of AJAX to connect Javascript and PHP. The way your PHP script works is by manually running the script, so only the device hitting that script will see the notification. There is nothing that actually sends that info to your other device right now.

为了更好地解释问题,您的桌面可能允许访问通知,但它不会自动提取这些通知.您提供的代码需要使用 AJAX 来访问脚本 URL,而不是将其用作 cron 作业.

To better explain the problem, your desktop may have allowed access to the notifications, but it doesn't automatically pull in those notifications. The code you have provided will need to use AJAX to hit the script URL, instead of using it as a cron job.

首先,您需要向 PHP 脚本发起重复请求,以查看是否有任何更新的通知.如果有新的通知,那么您需要使用返回的响应创建一个新的通知对象.

First off, you need to start a repeating request to the PHP script to see if there has been any updated notification. If there is a new notification, then you need to create a new notification object using the returned response.

其次,您需要修改 PHP 脚本以输出 JSON 字符串而不是通知脚本.

Second, you need to alter the PHP script to output a JSON string rather instead of the notification script.

JSON 输出示例:

{
  {
    title: 'new blog!',
    options: {
      body: 'come read my new blog!',
      icon: 'same icon as before or maybe a new one!'
    }
  },
  {
    title: 'another blog item!',
    options: {
      body: 'come read my second blog!',
      icon: 'hooray for icons!'
    }
  }
}

你的 notifyUsers() 应该将 titleoption 作为参数而不是硬编码它们:

Your notifyUsers() should take title and option as arguments instead of hardcoding them:

function notifyUser(title, options) { ... }

使用 jQuery,获取 PHP 响应并创建通知:

Using jQuery, get the PHP response and create the notification:

function checkNotifications(){
  $.get( "/path/to/script.php", function( data ) {
    // data is the returned response, let's parse the JSON string
    json = JSON.parse(data);

    // check if any items were returned
    if(!$.isEmptyObject(json)){
      // send each item to the notify function
      for(var i in json){
        notifyUser(json[i].title, json[i].options);
      }
    }
  });

  setTimeout(checkNotifications, 60000); // call once per minute
}

现在,您只需要启动 AJAX 轮询,将其添加到您的网页中:

Now, you just need to kickstart the AJAX polling, so add this to your webpage:

$(document).ready(checkNotifications);

差不多就是这样!当您的桌面需要接收通知时,您只是错过了这一部分.不过请注意,这尚未经过测试,您可能需要进行一些调整.

That's pretty much it! You were just missing the part when your desktop needed to pull in the notifications. Heads up though, this isn't tested and you may need to tweek something.

这篇关于使用 PHP 的 HTML5 通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆