{"id":19675942,"url":"https://github.com/yezihaohao/notification","last_synced_at":"2025-10-28T23:44:11.183Z","repository":{"id":93858885,"uuid":"82452541","full_name":"yezihaohao/notification","owner":"yezihaohao","description":"notification with socket.io","archived":false,"fork":false,"pushed_at":"2017-06-08T07:14:01.000Z","size":21,"stargazers_count":25,"open_issues_count":0,"forks_count":10,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-05T12:42:03.524Z","etag":null,"topics":["front-end","javascript","nodejs","notification","socket-io"],"latest_commit_sha":null,"homepage":null,"language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yezihaohao.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-02-19T10:55:17.000Z","updated_at":"2022-07-21T20:15:27.000Z","dependencies_parsed_at":"2023-03-13T17:09:45.757Z","dependency_job_id":null,"html_url":"https://github.com/yezihaohao/notification","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yezihaohao%2Fnotification","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yezihaohao%2Fnotification/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yezihaohao%2Fnotification/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yezihaohao%2Fnotification/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yezihaohao","download_url":"https://codeload.github.com/yezihaohao/notification/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251420890,"owners_count":21586697,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["front-end","javascript","nodejs","notification","socket-io"],"created_at":"2024-11-11T17:26:33.422Z","updated_at":"2025-10-28T23:44:11.107Z","avatar_url":"https://github.com/yezihaohao.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"### notification\nnotification with socket.io\n#### 1\nnpm install \n#### 2\nnode index.js\n#### 3\nopen the browser and visit http://localhost:8080/\n\n### 前言\n\u003e socket.io: 包含对websocket的封装，可实现服务端和客户端之前的通信。详情见[官网](http://socket.io) (虽然是英文文档，但还是通俗易懂)。\n  Notification: Html5新特性，用于浏览器的桌面通知，只有部分浏览器支持。\n  通过nodejs+Socket.io+Notification实现服务端往浏览器客户端发送自定义消息。\n  若有问题可加群264591039与我讨论。\n  转载请注明出处！\n  \n### 开发前提\n本地安装nodejs以及npm\n对nodejs以及express框架有一定了解。（本篇将和官方文档一样，采用express 4.10.2）\n\n### 环境搭建\n- 新建一个文件夹notification（以下操作都在该文件夹的根目录进行）\n- npm初始化package.json文件 `npm init`\n- 安装express(指定版本4.10.2，没有试过其他版本，感兴趣可以试下) `npm install --save express@4.10.2`\n- 安装socket.io(本人安装的版本是1.7.3) `npm install --save socket.io`\n\n### 编写代码\n#### 构建通信环境\n在根目录下新建一个index.html（注：index页面的样式来自socket.io的官方示例）\n```\n\u003c!doctype html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003ctitle\u003eSocket.IO Notification\u003c/title\u003e\n    \u003cstyle\u003e\n      * { margin: 0; padding: 0; box-sizing: border-box; }\n      body { font: 13px Helvetica, Arial; }\n      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }\n      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }\n      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }\n      #messages { list-style-type: none; margin: 0; padding: 0; }\n      #messages li { padding: 5px 10px; }\n      #messages li:nth-child(odd) { background: #eee; }\n    \u003c/style\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cul id=\"messages\"\u003e\u003c/ul\u003e\n    \u003cform action=\"\"\u003e\n      \u003cinput id=\"m\" autocomplete=\"off\" /\u003e\u003cbutton\u003eSend\u003c/button\u003e\n    \u003c/form\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n新建一个index.js文件，并在js文件中构建相应的对象和变量，创建监听端口为8080 的服务器，以及添加映射到index.html的路由。\n\n```bash\nlet express = require('express'),\n\tapp = express(),\n\thttp = require('http').Server(app),\n\tio = require('socket.io')(http);\napp.use(express.static(__dirname + '/public'));\n\napp.get('/', function(req, res){\n\tres.sendfile('index.html');\n});\n\nhttp.listen(8080, function(){\n\tconsole.log('listening on port 8080');\n});\n```\n运行 `node index.js` 用浏览器打开http://localhost:8080 成功的话即可看到index.html页面的内容。\n在index.js的监听端口代码上方添加socket.io的监听事件，监听用户连接的connection。\n```bash\nio.on('connection', function(socket){\n\tconsole.log('a user connected');\n});\n```\n创建监听Event事件:notification，并用emit向客户端推送消息\n```bash\nio.on('connection', function(socket){\n\tconsole.log('a user connected');\n\tsocket.on('notification', function(msg){\n\t\tconsole.log(msg);\n\t \tio.emit('notification', msg);\n\t});\n});\n```\n在index.html页面中的\u003c/body\u003e上方引入socket.io文件，并用emit向服务器提交数据以及监听事件notification，接收服务器推送的消息\n注意，引入socket.io的方式在运行`node index.js`之后才有效果，直接打开index.html是找不到这个文件的\n```bash\n    \u003cscript type=\"text/javascript\" src=\"/socket.io/socket.io.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"http://code.jquery.com/jquery-1.11.1.js\"\u003e\u003c/script\u003e\n    \u003cscript\u003e\n\t\tlet socket = io();\n\t\t$('form').submit(function(){\n\t\t\tsocket.emit('notification', $('#m').val());\n\t\t\t$('#m').val('');\n\t\t\treturn false;\n\t\t});\n\t\tsocket.on('notification', function(msg){\n\t\t\tconsole.log(msg);\n\t\t});\n    \u003c/script\u003e\n```\n浏览器打开http://localhost:8080 后，在input框中输入，点击发送，在nodejs运行的控制台可以看到如下信息：\n```bash\na user connected //以下数据是输入框输入的数据\nhello   \ntest\n测试\n```\n#### 实现自定义消息推送\n完整代码：\n```bash\n    \u003cscript\u003e\n\t\tlet socket = io();\n\t\t$('form').submit(function(){\n\t\t\tsocket.emit('notification', $('#m').val());\n\t\t\t$('#m').val('');\n\t\t\treturn false;\n\t\t});\n\t\tsocket.on('notification', function(msg){\n\t\t\tnotice(msg);    //若允许通知，待输入消息后监听变化就会调用通知方法\n\t\t});\n\n\t    Notification.requestPermission(function(permission) {});    //询问浏览器是否允许通知\n      \n\t\tfunction notice(msg) {  \n\t\t\tlet _notification = new Notification(`消息通知`,{\n\t\t\t\tbody:`${msg}`,\n\t\t\t\ticon:'http://localhost:8080/23539868.jpg'\n\t\t\t});\n\n\t\t\tsetTimeout(function(){\n\t\t\t\t_notification.close(); //设置5秒后自动关闭通知框\n\t\t\t},5000);\n\t\t  \n\t\t}\n    \u003c/script\u003e\n```\n### 运行截图\n\n完整示例代码见[GitHub](https://github.com/yezihaohao/notification)\n\n![截图](https://raw.githubusercontent.com/yezihaohao/yezihaohao.github.io/master/imgs/TEST.gif)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyezihaohao%2Fnotification","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyezihaohao%2Fnotification","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyezihaohao%2Fnotification/lists"}