Skip to content

Commit c17dba0

Browse files
authored
Merge pull request #117 from iMattPro/issue/105
Web push notification prompt message
2 parents 2a16e93 + 125154d commit c17dba0

File tree

13 files changed

+272
-0
lines changed

13 files changed

+272
-0
lines changed

acp/wpn_acp_module.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ public function display_settings()
108108
'WEBPUSH_VAPID_PRIVATE' => $this->config['wpn_webpush_vapid_private'] ? self::MASKED_PRIVATE_KEY : '',
109109
'S_WEBPUSH_DROPDOWN_SUBSCRIBE' => $this->config['wpn_webpush_dropdown_subscribe'],
110110
'S_WEBPUSH_METHOD_ENABLED' => $this->config['wpn_webpush_method_enabled'],
111+
'S_WEBPUSH_POPUP_PROMPT' => $this->config['wpn_webpush_popup_prompt'],
111112
'U_ACTION' => $this->u_action,
112113
]);
113114

@@ -133,6 +134,7 @@ public function save_settings()
133134
'wpn_webpush_vapid_private'=> ['validate' => 'string:25:255', 'lang' => 'WEBPUSH_VAPID_PRIVATE'],
134135
'wpn_webpush_dropdown_subscribe' => ['validate' => 'bool'],
135136
'wpn_webpush_method_enabled' => ['validate' => 'bool'],
137+
'wpn_webpush_popup_prompt' => ['validate' => 'bool'],
136138
];
137139

138140
// Do not validate and update private key field if the content is ******** and the key was already set

adm/style/wpn_acp_settings.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ <h3>{{ lang('WARNING') }}</h3>
3939
<dd><label><input type="radio" class="radio" name="config[wpn_webpush_method_enabled]" value="1" {% if S_WEBPUSH_METHOD_ENABLED %}checked="checked"{% endif %}> {{ lang('YES') }}</label>
4040
<label><input type="radio" class="radio" name="config[wpn_webpush_method_enabled]" value="0"{% if not S_WEBPUSH_METHOD_ENABLED %} checked="checked"{% endif %}> {{ lang('NO') }}</label></dd>
4141
</dl>
42+
<dl>
43+
<dt><label>{{ lang('WEBPUSH_POPUP_PROMPT') ~ lang('COLON') }}</label><br><span>{{ lang('WEBPUSH_POPUP_PROMPT_EXPLAIN') }}</span></dt>
44+
<dd><label><input type="radio" class="radio" name="config[wpn_webpush_popup_prompt]" value="1" {% if S_WEBPUSH_POPUP_PROMPT %}checked="checked"{% endif %}> {{ lang('YES') }}</label>
45+
<label><input type="radio" class="radio" name="config[wpn_webpush_popup_prompt]" value="0"{% if not S_WEBPUSH_POPUP_PROMPT %} checked="checked"{% endif %}> {{ lang('NO') }}</label></dd>
46+
</dl>
4247
</fieldset>
4348
<fieldset class="submit-buttons">
4449
<input class="button1" type="submit" id="submit" name="submit" value="{{ lang('SUBMIT') }}">&nbsp;

language/en/webpushnotifications_module_acp.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,7 @@
5050
'WEBPUSH_METHOD_ENABLED_EXPLAIN'=> 'When this setting is enabled, users who have also enabled and allowed browser notifications will start receiving them automatically. They can visit the UCP Notification settings to disable any unwanted notifications.<br><br>If this setting is disabled, users will not receive any notifications, even if they have enabled push notifications, until they visit the UCP Notification settings to allow the specific notifications they wish to receive.',
5151
'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Show web push settings in the notification dropdown',
5252
'WEBPUSH_DROPDOWN_SUBSCRIBE_EXPLAIN'=> 'Show or hide the “Enable Web Push” toggle switch in the notification dropdown. This allows users to easily enable or disable push notifications from any page of the forum.',
53+
'WEBPUSH_POPUP_PROMPT' => 'Show popup prompt for unsubscribed members',
54+
'WEBPUSH_POPUP_PROMPT_EXPLAIN' => 'Display a popup message asking registered members if they want to receive push notifications. The popup will only appear to members who are not currently subscribed and have not previously declined.',
5355
'WEBPUSH_INSECURE_SERVER_ERROR' => 'This board is not using a secure SSL/HTTPS protocol, which is required for enabling web push notifications. Alternatively, the server environment might be misconfigured. Ensure that the <em>HTTPS</em> and <em>HEADER_CLIENT_PROTO</em> server environment variables are correctly configured.',
5456
]);

language/en/webpushnotifications_module_ucp.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,8 @@
4949
'NOTIFY_WEBPUSH_DROPDOWN_TITLE' => 'Visit notifications settings to set your preferred push notifications.',
5050
'NOTIFY_WEBPUSH_DENIED' => 'You have denied notifications from this site. To enable push notifications, allow notifications from this site in your browser settings.',
5151
'NOTIFY_WEBPUSH_DISABLED' => 'Push notifications not supported',
52+
'NOTIFY_WEBPUSH_POPUP_TITLE' => 'Allow browser notifications?',
53+
'NOTIFY_WEBPUSH_POPUP_MESSAGE' => 'We would like to send you browser notifications for replies, private messages, and relevant forum activity. Optional — you can manage these settings at any time.',
54+
'NOTIFY_WEBPUSH_POPUP_ALLOW' => 'Allow',
55+
'NOTIFY_WEBPUSH_POPUP_DECLINE' => 'Decline',
5256
]);

language/ru/webpushnotifications_module_acp.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,7 @@
5050
'WEBPUSH_METHOD_ENABLED_EXPLAIN'=> 'Если включено, то пользователи, подписавшиеся на браузерные push—уведомления, будут автоматически получать все их типы. Если отключено, то пользователи не будут получать браузерные push—уведомления до тех пор, пока хотя бы один их тип не выбран.<br><br>Отключить нежелательные или выбрать нужные типы браузерных push—уведомлений можно в настройках уведомлений в Личном разделе.',
5151
'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Показать кнопку «Подписаться» в выпадающем меню уведомлений',
5252
'WEBPUSH_DROPDOWN_SUBSCRIBE_EXPLAIN'=> 'Включить или отключить отображение кнопки «Подписаться» в выпадающем списке уведомлений. Если включено, то пользователи смогут подписываться на браузерные push-уведомления с любой страницы конференции.',
53+
'WEBPUSH_POPUP_PROMPT' => 'Показывать всплывающее приглашение',
54+
'WEBPUSH_POPUP_PROMPT_EXPLAIN' => 'Показывать всплывающее сообщение зарегистрированным пользователям с приглашением подписаться на браузерные уведомления данной конференции. Сообщение будет показано только тем зарегистрированным пользователям, которые не подписаны на браузерные уведомления и ранее не отклоняли такое приглашение.',
5355
'WEBPUSH_INSECURE_SERVER_ERROR' => 'На данной конференции не применяется защищённый протокол SSL/HTTPS, без которого использование браузерных push—уведомлений невозможно, либо соответствующие переменные серверного окружения неверно сконфигурированы. Убедитесь, что значения переменных серверного окружения <em>HTTPS</em> и/или <em>HEADER_CLIENT_PROTO</em> заданы верно.',
5456
]);

language/ru/webpushnotifications_module_ucp.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,8 @@
4949
'NOTIFY_WEBPUSH_DROPDOWN_TITLE' => 'Посетите настройки уведомлений, чтобы установить предпочтительные типы браузерных уведомлений.',
5050
'NOTIFY_WEBPUSH_DENIED' => 'Вы запретили браузерные уведомления для даного сайта. Для того, чтобы подписаться, необходимо их разрешить в настройках браузера.',
5151
'NOTIFY_WEBPUSH_DISABLED' => 'Не поддерживается',
52+
'NOTIFY_WEBPUSH_POPUP_TITLE' => 'Включить браузерные уведомления?',
53+
'NOTIFY_WEBPUSH_POPUP_MESSAGE' => 'Браузерные уведомления позволяют быстро получать информацию о новых ответах, личных сообщениях и других активностях на данной конференции. Функцию можно отключить или включить в любое время в настройках уведомлений в Личном разделе.',
54+
'NOTIFY_WEBPUSH_POPUP_ALLOW' => 'Включить',
55+
'NOTIFY_WEBPUSH_POPUP_DECLINE' => 'Отклонить',
5256
]);

migrations/add_popup_prompt.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
/**
3+
*
4+
* phpBB Browser Push Notifications. An extension for the phpBB Forum Software package.
5+
*
6+
* @copyright (c) 2025, phpBB Limited <https://www.phpbb.com>
7+
* @license GNU General Public License, version 2 (GPL-2.0)
8+
*
9+
*/
10+
11+
namespace phpbb\webpushnotifications\migrations;
12+
13+
use phpbb\db\migration\migration;
14+
15+
class add_popup_prompt extends migration
16+
{
17+
public function effectively_installed()
18+
{
19+
return $this->config->offsetExists('wpn_webpush_popup_prompt');
20+
}
21+
22+
public static function depends_on()
23+
{
24+
return ['\phpbb\webpushnotifications\migrations\add_acp_configs'];
25+
}
26+
27+
public function update_data()
28+
{
29+
return [
30+
['config.add', ['wpn_webpush_popup_prompt', 0]],
31+
];
32+
}
33+
}

notification/method/webpush.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ public function get_ucp_template_data(helper $controller_helper, form_helper $fo
394394
'U_WEBPUSH_WORKER_URL' => $controller_helper->route('phpbb_webpushnotifications_ucp_push_worker_controller'),
395395
'SUBSCRIPTIONS' => $subscriptions,
396396
'WEBPUSH_FORM_TOKENS' => $form_helper->get_form_tokens(\phpbb\webpushnotifications\ucp\controller\webpush::FORM_TOKEN_UCP),
397+
'S_WEBPUSH_POPUP_PROMPT' => $this->config['wpn_webpush_popup_prompt'] && $this->user->id() != ANONYMOUS && $this->user->data['user_type'] != USER_IGNORE,
397398
];
398399
}
399400

styles/all/template/event/overall_header_head_append.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@
1111

1212
{% if NOTIFICATIONS_WEBPUSH_ENABLE %}
1313
{% include '@phpbb_webpushnotifications/ucp_notifications_webpush.html' %}
14+
{% include '@phpbb_webpushnotifications/webpush_popup.html' %}
1415
{% endif %}

styles/all/template/webpush.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ function PhpbbWebpush() {
6262
unsubscribeButton.addEventListener('click', unsubscribeButtonHandler);
6363

6464
updateButtonState();
65+
initPopupPrompt();
6566
})
6667
.catch(error => {
6768
console.info(error);
@@ -116,6 +117,75 @@ function PhpbbWebpush() {
116117
}
117118
}
118119

120+
/**
121+
* Initialize popup prompt
122+
*/
123+
function initPopupPrompt() {
124+
const popup = document.getElementById('wpn_popup_prompt');
125+
if (!popup || Notification.permission === 'denied') {
126+
return;
127+
}
128+
129+
// Check if user declined on this browser
130+
if (getDeclined() === 'true') {
131+
return;
132+
}
133+
134+
// Check if this browser already has a subscription
135+
navigator.serviceWorker.getRegistration(serviceWorkerUrl)
136+
.then(registration => {
137+
if (typeof registration === 'undefined') {
138+
showPopup(popup);
139+
return;
140+
}
141+
142+
registration.pushManager.getSubscription()
143+
.then(subscription => {
144+
if (!isValidSubscription(subscription)) {
145+
showPopup(popup);
146+
}
147+
});
148+
});
149+
}
150+
151+
/**
152+
* Show popup with event handlers
153+
*/
154+
function showPopup(popup) {
155+
setTimeout(() => {
156+
popup.style.display = 'flex';
157+
}, 1000);
158+
159+
const allowBtn = document.getElementById('wpn_popup_allow');
160+
const declineBtn = document.getElementById('wpn_popup_decline');
161+
const overlay = document.getElementById('wpn_popup_prompt');
162+
163+
if (allowBtn) {
164+
allowBtn.addEventListener('click', (event) => {
165+
event.stopPropagation();
166+
popup.style.display = 'none';
167+
subscribeButtonHandler({ preventDefault: () => {} });
168+
});
169+
}
170+
171+
if (declineBtn) {
172+
declineBtn.addEventListener('click', (event) => {
173+
event.stopPropagation();
174+
popup.style.display = 'none';
175+
setDeclined();
176+
});
177+
}
178+
179+
if (overlay) {
180+
overlay.addEventListener('click', (event) => {
181+
if (event.target === overlay) {
182+
popup.style.display = 'none';
183+
setDeclined();
184+
}
185+
});
186+
}
187+
}
188+
119189
/**
120190
* Check whether subscription is valid
121191
*
@@ -258,6 +328,11 @@ function PhpbbWebpush() {
258328
if ('form_tokens' in response) {
259329
updateFormTokens(response.form_tokens);
260330
}
331+
resetDeclined();
332+
const popup = document.getElementById('wpn_popup_prompt');
333+
if (popup) {
334+
popup.style.display = 'none';
335+
}
261336
}
262337
}
263338

@@ -303,6 +378,16 @@ function PhpbbWebpush() {
303378

304379
return outputArray;
305380
}
381+
382+
function setDeclined() {
383+
localStorage.setItem('wpn_popup_declined', 'true');
384+
}
385+
function getDeclined() {
386+
return localStorage.getItem('wpn_popup_declined');
387+
}
388+
function resetDeclined() {
389+
localStorage.removeItem('wpn_popup_declined');
390+
}
306391
}
307392

308393
function domReady(callBack) {

0 commit comments

Comments
 (0)