PageSourceSearch

https://bntnews.bg/box2/js/onesignal-init.js?p=1560

js bntnews.bg collected 2026-10-02 02:29:24 UTC 15,143 bytes, 404 lines download raw bytes

1(function(config) {
2    // Exit early if notifications shouldn't be initialized
3    if (config.isApp || !config.allowBrowserNoty) {
4        return;
5    }
6
7    // Configuration
8    var ONESIGNAL_APP_ID = "fce0fdc3-636c-460e-a6db-de0c4ee85de6";
9    var SAFARI_WEB_ID = "web.onesignal.auto.5462a642-4744-4944-be08-d03aa1430cc8";
10    var NOTIFICATION_TIMEOUT = 9000;
11    var ERROR_MESSAGE = "За да се абонирате трябва да разрешите нотификации във браузъра. Можете да направите това от катинарчето в горната чат на браузъра ви до адреса на сайта.";
12
13    // State management
14    var notificationState = "";
15    var notificationRequestTimeout = null;
16
17    // DOM element selectors
18    var selectors = {
19        agreeButton: "#agreeNotificationsButton",
20        agreeButtonDesktop: "#agreeNotificationsButtonDesk",
21        notificationBoxDesktop: ".noty-ask-box.show-desktop",
22        notificationBoxMobile: ".noty-ask-box.hide-
22desktop",
23        stickyContainer: "#stickySubscribeContainer"
24    };
25
26    /**
27     * Get the current subscription state
28     * @returns {Promise} Promise that resolves to subscription state info
29     */
30    function getSubscriptionState() {
31        return Promise.all([
32            OneSignal.isPushNotificationsEnabled(),
33            OneSignal.isOptedOut()
34        ]).then(function(results) {
35            var isPushEnabled = results[0];
36            var isOptedOut = results[1];
37
38            return {
39                isPushEnabled: isPushEnabled,
40                isOptedOut: isOptedOut,
41                isSubscribed: isPushEnabled && !isOptedOut
42            };
43        }).catch(function(error) {
44            // console.error("Error getting subscription state:", error);
45            return {
46                isPushEnabled: false,
47                isOptedOut: false,
48                isSubscribed: false
49            };
50        });
51    }
52
53    /**
54     * Update UI state
55     * @param {string} state - The state to update to
56     */
57    function updateState(state) {
58        notificationState = state;
59
60        // Additional UI updates based on state could be added here
61    }
62
63    /**
64     * Show notification permission request
65     */
66     function triggerAction() {
67         // Update UI state to loading
68         updateState('loading');
69
70         // Update UI of all buttons to loading state
71         var stickyContainer = document.querySelector(selectors.stickyContainer);
72         // Get additional buttons that are outside the container
73         var yesButtonOne = document.querySelector('#subscribeYesOne');
74         var noButtonOne = document.querySelector('#subscribeNoOne');
75
76         if (stickyContainer) {
77             var yesButton = stickyContainer.querySelector('#subscribeYes');
78             var noButton = stickyContainer.querySelector('#subscribeNo');
79
80             if (yesButton) {
81                 yesButton.innerHTML = "Моля изчакайте ...";
82                 yesButton.disabled = true;
83             }
84             if (noButton) {
85                 noButton.disabled = false;
86             }
87             if (yesButtonOne) {
88                 yesButtonOne.innerHTML = "Моля изчакайте ...";
89                 yesButtonOne.disabled = true;
90             }
91             if (noButtonOne) {
92                 noButtonOne.disabled = false;
93             }
94         }
95
96         // Update other UI elements
97         $(selectors.agreeButton).html("Моля изчакайте ...");
98         $(selectors.agreeButtonDesktop).html("Моля изчакайте ...");
99
100         // Clear any existing timeout
101         if (notificationRequestTimeout) {
102             clearTimeout(notificationRequestTimeout);
103         }
104
105         // Get current subscription state
106         getSubscriptionState().then(function(subscriptionState) {
107             if (subscriptionState.isOptedOut || subscriptionState.isPushEnabled) {
108                 // User already has a subscription state, just enable it
109                 // console.log("User already has subscription state, enabling it");
110                 OneSignal.setSubscription(true);
111                 refresh();
112                 return;
113             }
114
115             // User needs to give permission - directly request browser permission
116             // console.log("Requesting browser notification permission");
117
118             // This is the key change - directly trigger the browser permission dialog
119             OneSignal.registerForPushNotifications({
120                 modalPrompt: false  // Don't use OneSignal's custom UI
121             }).then(function() {
122                 // Permission was granted
123                 // console.log("Permission granted");
124                 refresh();
125             }).catch(function(error) {
126                 // console.log("Error or permission denied:", error);
127                 // Reset the UI
128                 resetButtonsUI(stickyContainer, yesButton, noButton, yesButtonOne, noButtonOne);
129             });
130
131             // Set a timeout as a fallback in case OneSignal promise doesn't resolve
132             notificationRequestTimeout = setTimeout(function() {
133                 // console.log("Checking permission state after timeout");
134                 getSubscriptionState().then(function(updatedState) {
135                     if (!updatedState.isPushEnabled) {
136                         console.log("Permission not granted after timeout");
137                         // Optionally show error message
138                         // noty({
139                         //     "text": ERROR_MESSAGE,
140                         //     "info": "error"
141                         // });
142                     } else {
143                         console.log("Permission granted after timeout");
144                         refresh();
145                     }
146
147                     // Reset UI regardless of outcome
148                     resetButtonsUI(stickyContainer, yesButton, noButton, yesButtonOne, noButtonOne);
149                 });
150             }, NOTIFICATION_TIMEOUT);
151         }).catch(function(error) {
152             console.log("Error getting subscription state:", error);
153             resetButtonsUI(stickyContainer, yesButton, noButton, yesButtonOne, noButtonOne);
154         });
155
156         // Helper function to reset UI
157         function resetButtonsUI(stickyContainer, yesButton, noButton, yesButtonOne, noButtonOne) {
158             $(selectors.agreeButton).html("Да");
159             $(selectors.agreeButtonDesktop).html("Да");
160
161             if (stickyContainer) {
162                 if (yesButton) {
163                     yesButton.innerHTML = "ДА";
164                     yesButton.disabled = false;
165                 }
166                 if (noButton) {
167                     noButton.disabled = false;
168                 }
169             }
170
171             // Reset the external buttons regardless of stickyContainer
172             if (yesButtonOne) {
173                 yesButtonOne.innerHTML = "ДА";
174                 yesButtonOne.disabled = false;
175             }
176             if (noButtonOne) {
177                 noButtonOne.disabled = false;
178             }
179         }
180     }
181
182    /**
183     * Register for push notifications
184     */
185    function registerForNotifications() {
186        OneSignal.registerForPushNotifications();
187        triggerAction();
188    }
189
190    /**
191     * Handle user accepting notifications
192     */
193    function acceptNotifications() {
194        triggerAction();
195    }
196
197    /**
198     * Block notifications and redirect
199     */
200    function blockNotifications() {
201        OneSignal.setSubscription(false);
202
203        $.post("/me/stopnoty", function(data) {
204            window.location = "/personal";
205        }, "json");
206    }
207
208    /**
209     * Don't show notification prompt again for a specific time period (2 months)
210     */
211    function dismissNotificationPrompt() {
212        $.post("/me/blocknoty", function(data) {
213            $(".noty-ask-box").slideUp(200);
214
215            // Hide sticky container
216            var stickyContainer = document.querySelector(selectors.stickyContainer);
217            if (stickyContainer) {
218                stickyContainer.classList.remove('visible');
219
220                // Store preference in localStorage along with timestamp
221                try {
222                    // Store current time as expiration reference
223                    var currentTime = new Date().getTime();
224                    localStorage.setItem('neverShowNotifications', 'true');
225                    localStorage.setItem('neverShowNotificationsTimestamp', currentTime);
226                } catch (e) {
227                    // Silent fail if localStorage is not available
228                }
229            }
230
231            if($("#reloadAfterAction")[0]) {
232                location.reload();
233            }
234        }, "json");
235    }
236
237    /**
238     * Refresh subscription state and update server
239     */
240    function refresh() {
241        updateState('loading');
242
243        getSubscriptionState().then(function(subscriptionState) {
244            updateState(subscriptionState.isSubscribed ? 'subscribed' : 'not-subscribed');
245
246            if (subscriptionState.isSubscribed) {
247                // Hide sticky container if user is subscribed
248                var stickyContainer = document.querySelector(selectors.stickyContainer);
249                if (stickyContainer) {
250                    stickyContainer.classList.remove('visible');
251                }
252                OneSignal.getUserId(function(userId) {
253                    $.post("/me/allownoty", { "id": userId }, function(data) {
254                        if (config.myActive) {
255                            if($("#reloadAfterAction")[0]) {
256                                window.location = "/personal";
257                            }
258                            else {
259                                location.reload();
260                            }
261                        } else {
262                            window.location = "/personal";
263                        }
264                    }, "json");
265                });
266            }
267        }).catch(function(error) {
268            // console.error("Error refreshing notification state:", error);
269        });
270    }
271
272    /**
273     * Show notification prompt if necessary
274     */
275    function initializeNotificationPrompt() {
276        // Check if user has chosen to never show notifications
277        var neverShow = false;
278
279        try {
280            // Get the stored preference
281            var neverShowPref = localStorage.getItem('neverShowNotifications') === 'true';
282
283            if (neverShowPref) {
284                // Check if it's been more than 2 months since user dismissed notifications
285                var storedTime = parseInt(localStorage.getItem('neverShowNotificationsTimestamp') || '0');
286                var currentTime = new Date().getTime();
287                var twoMonthsInMs = 60 * 24 * 60 * 60 * 1000; // 60 days in milliseconds
288
289                // If less than 2 months have passed, keep neverShow true
290                // If more than 2 months, reset to false to show the prompt again
291                neverShow = (currentTime - storedTime) < twoMonthsInMs;
292
293                // If more than 2 months have passed, clear the stored preference
294                if (!neverShow) {
295                    localStorage.removeItem('neverShowNotifications');
296                    localStorage.removeItem('neverShowNotificationsTimestamp');
297                }
298            }
299        } catch (e) {
300            // Silent fail if localStorage is not available
301        }
302
303        // Get additional buttons that are outside the container
304        var yesButtonOne = document.querySelector('#subscribeYesOne');
305        var noButtonOne = document.querySelector('#subscribeNoOne');
306
307        // Add event listeners to external buttons
308        if (yesButtonOne) {
309            yesButtonOne.addEventListener('click', function() {
310                acceptNotifications();
311            });
312        }
313        if (noButtonOne) {
314            noButtonOne.addEventListener('click', function() {
315                dismissNotificationPrompt();
316            });
317        }
318
319        if (neverShow) {
320            return;
321        }
322        getSubscriptionState().then(function(subscriptionState) {
323            if (subscriptionState.isSubscribed) {
324                OneSignal.getUserId(function(userId) {
325                    $.post("/me/stillsubscribed", { "id": userId });
326                });
327            } else {
328                // Show standard notification prompt
329                $(selectors.notificationBoxMobile).removeClass("none-important");
330
331                if (config.browserId && config.myActive && !config.reloaded) {
332                    $.post("/me/blocknoty", function(data) {
333                        window.location = "/personal?reloaded=1";
334                    }, "json");
335                }
336
337
338                // Show the sticky notification box
339                var stickyContainer = document.querySelector(selectors.stickyContainer);
340                if (stickyContainer) {
341                    // Add event listeners to the buttons
342                    var yesButton = stickyContainer.querySelector('#subscribeYes');
343                    var noButton = stickyContainer.querySelector('#subscribeNo');
344
345                    if (yesButton) {
346                        yesButton.addEventListener('click', function() {
347                            acceptNotifications();
348                        });
349                    }
350
351                    if (noButton) {
352                        noButton.addEventListener('click', function() {
353                            dismissNotificationPrompt();
354                        });
355                    }
356
357
358
359                    // Show the container with a small delay for better UX
360                    setTimeout(function() {
361                        stickyContainer.classList.add('visible');
362                    }, 2000);
363                }
364            }
365        }).catch(function(error) {
366            // console.error("Error initializing notification prompt:", error);
367        });
368    }
369
370    // Initialize OneSignal
371    window.OneSignal = window.OneSignal || [];
372    OneSignal.push(function() {
373        // Return if push notifications aren't supported
374        if (!OneSignal.isPushNotificationsSupported()) {
375            return;
376        }
377
378        // Set log level
379        OneSignal.log.setLevel('warn');
380
381        // Initialize notification prompt
382        initializeNotificationPrompt();
383
384        // Initialize OneSignal with configuration
385        OneSignal.init({
386            appId: ONESIGNAL_APP_ID,
387            safari_web_id: SAFARI_WEB_ID,
388            notifyButton: {
389                enable: false,
390                showCredit: false
391            }
392        });
393
394        // Set up subscription change event handler
395        OneSignal.on('subscriptionChange', refresh);
396    });
397
398    // Expose public functions
399    window.registerNoty = registerForNotifications;
400    window.wantsNoty = acceptNotifications;
401    window.blockNoty = blockNotifications;
402    window.donwWantNoty = dismissNotificationPrompt;
403
404})(window.oneSignalConfig || {});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.