Select Page
開發人員必看的 Web Push 功能教學

開發人員必看的 Web Push 功能教學

Web Push 是一種標準的 Web 協議,允許網站向使用者發送推播通知。這項功能可用於各種目的,例如:

  • 提醒使用者有新的內容或更新
  • 提供即時通知,例如交易狀態或聊天訊息
  • 提高使用者參與度

準備工作

  • 前端訂閱推播服務的 js 檔案
  • 前端訂閱推播服務的網頁,需要包含訂閱服務的 js
  • 後端紀錄使用者訂閱資訊的服務
  • 後端推播訊息的服務
  • 後端註冊訊息伺服器的程式碼

建立前端網頁的訂閱表單

這個檔案將包含安裝、激活、攔截請求和推播事件的處理器。創建一個名為sw.js的檔案,並將其放在你網站的根目錄下

// 安裝Service Worker
self.addEventListener('install', function(event) {
    console.log('Service Worker 安裝成功');
});

// Service Worker 激活
self.addEventListener('activate', function(event) {
    console.log('Service Worker 激活成功');
});

// 監聽推播事件
self.addEventListener('push', function(event) {
    var title = '推播通知';
    var options = {
        body: '這是一條推播消息。',
        icon: 'icon.png',
        badge: 'badge.png'
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

在你的網站上註冊一個Service Worker,這是實現Web推播的必要步驟。Service Worker將在背景執行,即使用戶沒有直接訪問你的網站也能接收通知。通常會把下面的 javascript 寫在首頁中,觸發訂閱的條件。

// 在主要的JavaScript檔案中
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;
}

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    console.log('Service Worker 注册成功:', registration);
  }).catch(function(error) {
    console.log('Service Worker 注册失败:', error);
  });
}
navigator.serviceWorker.ready.then(function(registration) {
  if (!registration.pushManager) {
    alert('此瀏覽器不支持推播通知');
    return false;
  }
const applicationServerKey = 'your publice key';
  
// 訂閱推播
  registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(applicationServerKey)
  }).then(function(subscription) {
    console.log('推播訂閱成功:', subscription);

    // 發送訂閱資訊到後端
    fetch('https://your_webpush_server/subscribe', {
      method: 'post',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({
        subscription: subscription
      }),
    });
  }).catch(function(error) {
    console.log('推播訂閱失败:', error);
  });

提供紀錄訂閱訊息的服務

這一段的作法很多,通常用你原本伺服器中的解決方案,例如 php,asp.net,nodejs,python,GO等,我這邊為了方便,用nodejs示範下

const express = require('express');
const cors = require('cors');

const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());

const subscriptions = {}; // 在實際應用中,應使用資料庫儲存訂閱資訊

const webPush = require('web-push');
    // 設置你的VAPID鑰匙
    webPush.setVapidDetails(
        'mailto:[email protected]',
      	'your publiec key',
      	'your private key'
      };

app.post('/subscribe', (req, res) => {
    const subscription = req.body;
    const key = subscription.endpoint; // 使用endpoint作為唯一鑰匙
    subscriptions[key] = subscription;

    console.log('subscripted');
    console.log(subscription);
    
    // subscription是從前端發送到後端的訂閱對象
    webPush.sendNotification(subscription.subscription, '消息內容')
        .then(result => console.log('推播成功'))
        .catch(err => console.log('推播失敗', err));

    res.status(200).json({message: '訂閱成功'});
});

app.listen(8060, () => console.log('伺服器運行在8060端口'));

其中 sendNotification 平常應該是要放在 webpush service中的,這邊加入是用來測試使用

生成VAPID鑰匙 (自願應用伺服器身份驗證)

大部分現代瀏覽器(如Chrome、Firefox、Edge)都支持Web推播API,但是如果你不用市面上的解決方案如 OneSignal 而是要直接與這些瀏覽器的推播服務交互的話,需要使用VAPID(自願應用伺服器身份驗證)鑰匙進行身份驗證。

生成 VAPID Key 的方法如下

npx web-push generate-vapid-keys

記住保存生成的鑰匙。公鑰將在前端用於訂閱推播,私鑰將在後端用於發送推播。


如果你無法使用npx(它通常隨npm自動安裝,作為npm 5.2.0及更高版本的一部分),那麼你可以通過下載最新版本的 nodejs

https://nodejs.org/

或是升級Node.js,或使用版本管理器如nvm(Node Version Manager)來管理不同版本的Node.js。

參考資料

https://developer.mozilla.org/en-US/docs/Web/API/Push_API

Electric Rice Cooker Magic: Turning Simple Grains into Culinary Delights

Electric Rice Cooker Magic: Turning Simple Grains into Culinary Delights


Cooking rice in a rice cooker may seem straightforward, but achieving the perfect texture and flavor that makes each grain distinct and delicious is an art. Here, we share six key tips for using a standard electric rice cooker that will instantly upgrade your rice, making it more flavorful and enjoyable. These steps are tailored to guide pasta-loving foreigners on how to master the art of cooking incredibly tasty white rice with a rice cooker, transitioning from the initial rice washing to the moment the rice is perfectly cooked.

Step 1: Washing the Rice

When washing rice, speed and a gentle touch are crucial to remove dust and excess starch without breaking the grains.

Step 2: Adding Water

The golden ratio of rice to water is 1:1.2, as revealed by culinary experts. This ratio ensures the rice is neither too hard nor too soft.

Step 3: Soaking

It’s recommended to soak the rice for about half an hour in summer and extend the soaking time to 1.5 hours in winter. This step ensures the grains fully absorb water, leading to a better texture after cooking.

Step 4: Cooking the Rice

Before starting the rice cooker, add a little salad oil and white vinegar to the soaked rice. This trick not only gives the rice an extra shine and a beautiful white color but also enhances its flavor, making it more appealing.

Step 5: Letting the Rice Steam

After the cooking cycle completes, let the rice sit and steam for about 5 to 10 minutes before opening the lid. This allows the rice to finish cooking in its own steam, improving its texture.

Step 6: Fluffing the Rice

Fluffing the cooked rice with a fork or rice paddle before serving ensures that the grains are separate and not clumpy. This step is vital for achieving a uniform texture throughout the pot.

By following these simple yet effective tips, even those accustomed to pasta can easily cook delicious white rice using an electric rice cooker. Each step, from washing the rice to fluffing it before serving, is designed to enhance the rice’s natural flavor and texture, turning a simple grain into a delightful accompaniment to any meal.

Electric Rice Cooker Magic: Turning Simple Grains into Culinary Delights

從洗米到鬆飯:電鍋煮出美味白飯的六大技巧


煮出一鍋香Q、粒粒分明的白米飯,對許多人來說是每天的必需,但想要將這個日常行為升級成為一種藝術,則需要掌握一些關鍵的技巧。使用電鍋煮飯,雖然簡單方便,但要讓米飯達到完美的口感和香氣,就需要遵循以下六個步驟,從洗米開始,到最終的鬆飯階段,每一步都藏有提升飯質的小秘訣。

第1步:洗米

洗米是煮飯過程中的第一步,也是極為重要的一步。正確的洗米方法可以去除米粒表面的多餘澱粉和灰塵,防止煮出來的飯黏稠或是有異味。洗米時,手法需快速且輕巧,這樣才能有效清洗而不破壞米粒。

第2步:加水

加水量直接影響到米飯的口感。一般來說,米與水的黃金比例是1:1.2,這個比例適合大多數的電鍋,能煮出既不過硬也不過軟的白飯。

第3步:浸泡

根據季節的不同,浸泡米的時間也應有所調整。夏天的時候,因為氣溫較高,浸泡半小時左右即可;而在冬天,則建議將浸泡時間延長至1.5小時,這樣可以確保米粒吸足水分,煮出來的米飯更加鬆軟。

第4步:煮飯

在煮飯之前,在浸泡好的米中加入少量的沙拉油和白醋,是一個小技巧。沙拉油可以讓米飯更加閃亮,而白醋則有助於讓米飯顏色更加純白,增加飯菜的美觀和食慾。

第5步:悶飯

米飯煮好後,不要急著打開電鍋蓋。讓米飯在鍋中悶5到10分鐘,可以讓米飯吸收剩餘的水分,變得更加香Q。

第6步:鬆飯

煮好的米飯在悶好之後,打開鍋蓋,用飯匙輕輕拌勻。這個動作不僅可以幫助米飯散熱,還能確保每一粒米飯都能均勻吸收水分和香氣,達到整鍋米飯口感一致的效果。

洗快且輕、泡水、1:1.2、少量油、再悶一下

洗米水拿去澆花

掌握了這些小訣竅,就能在家用電鍋煮出一鍋又香又Q的白米飯。這些步驟雖然簡單,但每一步都蘊含著對食材的尊重和對烹飪的熱愛,讓日常的米飯變成一頓美味的盛宴。

如何使用DeepBrain AI立即生成數字主播視頻”

如何使用DeepBrain AI立即生成數字主播視頻”

DeepBrain AI 是一家專注於人工智能技術開發的公司,其創新的AI Video Generator Online平台能夠通過簡單的文字輸入、網址提供或上傳PPT文件,迅速生成一個數字化的主播來講解提供的內容。這項技術不僅改變了內容創建的方式,也為教育、新聞、營銷等多個領域帶來了革命性的影響。

文字轉換視頻

使用DeepBrain AI的AI Video Generator,用戶可以僅通過輸入文字來創建視頻內容。這項技術使用先進的自然語言處理(NLP)來理解文字內容,並將其轉換為數字主播的語音。這意味著用戶可以快速製作新聞報導、產品介紹或任何其他類型的視頻內容,而無需實際拍攝視頻。

網址內容轉換

除了文字輸入之外,DeepBrain AI的平台還允許用戶提供一個網址,系統將自動提取該網頁上的內容,並生成一段由數字主播講解的視頻。這對於想要快速轉換網絡文章或博客為視頻內容的用戶來說,是一個非常有用的功能。

上傳PPT轉換視頻

對於需要將演示文稿轉換為視頻教程或演講的用戶,DeepBrain AI提供了上傳PPT文件的功能。平台將自動分析PPT中的內容,包括文本和圖像,並創建一個數字主播來講解這些內容。這使得教育者和企業專業人士能夠以更互動和吸引人的方式分享他們的知識和信息。

輸出到YouTube

一旦視頻內容被創建,DeepBrain AI的平台還支持將視頻直接上傳到YouTube,這為用戶提供了一種便捷的方式來分享和分發他們的內容。通過這種方式,用戶可以輕鬆地將他們的數字主播創建的視頻推廣到更廣泛的觀眾。

如何用LeiaPix將你的照片轉變為迷人的3D動畫

如何用LeiaPix將你的照片轉變為迷人的3D動畫

LeiaPix是一款創新的科技產品,它利用先進的人工智能技術將平面圖片轉換成3D動畫,為用戶提供了全新的視覺體驗。這項技術尤其擅長處理人物照片,能夠將靜態的2D影像轉化成仿佛跳躍出畫面的3D動態畫面,讓照片中的人物顯得更加生動、立體。

LeiaPix的工作原理是通過深度學習算法分析2D圖像中的視覺信息,如顏色、形狀、紋理等元素,並推測出圖像背後的3D結構。這包括對圖像中人物的姿態、面部表情以及與背景的相對位置進行精確解析。接著,AI利用這些信息構建出一個3D模型,並將其動畫化,使圖像中的人物仿佛被賦予了生命。

一個重要的特點是LeiaPix的用戶界面非常友好,不需要專業的3D建模技能,用戶只需上傳一張平面照片,剩下的工作就交給AI來完成。這使得任何人都能輕鬆地將自己的照片轉換成3D動畫,無論是用於社交媒體分享、個人收藏,還是作為創意項目的一部分。

此外,LeiaPix的應用範圍非常廣泛,它不僅可以用於人物照片的轉換,也適用於風景、物品等其他類型的圖片。這意味著用戶可以將任何記憶中的瞬間轉換成3D動畫,增加了與照片互動的趣味性和沉浸感。

在商業應用方面,LeiaPix也展現出巨大的潛力。例如,它可以用於廣告創意的製作,通過3D動畫吸引更多的目光;或者在電子商務中,將商品照片轉化成3D動畫,提供給消費者更直观的商品展示。