// Sayfanın yüklenmesi tamamlandığında çalışır
window.addEventListener("load", async () => {
try {
// Firebase modüllerini yükle
await import("/script-diger-s-firebase-app.js");
await import("/script-diger-s-firebase-messaging.js");
// Firebase yapılandırma bilgileri
const firebaseConfig = {
apiKey: "AIzaSyBEjyAphWnkJ__-sNlfW17G5zeSo6UcoCI",
authDomain: "postlisting-6bcc0.firebaseapp.com",
projectId: "postlisting-6bcc0",
storageBucket: "postlisting-6bcc0.appspot.com",
messagingSenderId: "639060170034",
appId: "1:639060170034:web:443582dfdf91a75d73f32b" };
// Firebase'i başlat
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
// Bildirim iznini kontrol et
checkNotificationPermission();
// iOS'ta PWA kurulum uyarısı gösteren fonksiyon
function showPWAInstallPrompt() {
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
const isSafari = /Safari/i.test(navigator.userAgent) && !/CriOS|Chrome|EdgiOS|Brave/i.test(navigator.userAgent);
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.2);
z-index: 1000; text-align: center; max-width: 90%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
`;
dialog.innerHTML = isSafari
? `
Turn on notifications for unmissable deals!
In Safari, add the site via Share (⬆️) > Add to Home Screen.
`
: `
Please use Safari browser for notifications!
Open the site in Safari and use Share (⬆️) > Add to Home Screen.
`;
document.body.appendChild(dialog);
}
}
// Bildirim iznini kontrol eden fonksiyon
function checkNotificationPermission() {
// iOS'ta Safari ve PWA kontrolü
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
const isSafari = /Safari/i.test(navigator.userAgent) && !/CriOS|Chrome|EdgiOS|Brave/i.test(navigator.userAgent);
if (!isSafari || !window.matchMedia('(display-mode: standalone)').matches) {
showPWAInstallPrompt();
return;
}
}
let gco = parseInt(getCookie('bizin')) || 0;
// Eğer izin zaten verilmişse, token oluştur
if (Notification.permission === "granted") {
generateToken();
return;
}
// Eğer izin reddedilmişse, yalnızca bir kez uyarı göster
if (Notification.permission === "denied" && !sessionStorage.getItem('denied_shown')) {
showPermissionDeniedMessage();
sessionStorage.setItem('denied_shown', '1');
return;
}
// Çerez kontrolü: İlk kez veya ikinci kez göster
if (!gco) {
setCookie('bizin', 1, 1);
showNotificationPrompt();
} else if (gco > 1) {
return;
} else {
setCookie('bizin', gco + 1, 1);
showNotificationPrompt();
}
}
// Tarayıcıyı tespit eden yardımcı fonksiyon
function detectBrowser() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.includes("edg/")) return "edge";
if (userAgent.includes("chrome") && !userAgent.includes("edg/")) return "chrome";
if (userAgent.includes("firefox")) return "firefox";
if (userAgent.includes("safari") && !userAgent.includes("chrome")) return "safari";
if (userAgent.includes("brave")) return "brave";
return "other";
}
// Bildirim izni reddedildiğinde tarayıcıya özel uyarı gösteren fonksiyon
function showPermissionDeniedMessage() {
const browser = detectBrowser();
let instructions;
switch (browser) {
case "edge":
instructions = `Turn on notification permission in your Microsoft Edge settings:
Menu (three dots) > Settings > Cookies and site permissions > Notifications > Set permission for "${window.location.hostname}" to "Ask".`;
break;
case "chrome":
instructions = `Enable notification permission in your Google Chrome settings:
Menu (three dots) > Settings > Privacy and security > Site settings > Notifications > Set permission for "${window.location.hostname}" to "Allow".`;
break;
case "firefox":
instructions = `Enable notification permission in your Firefox settings:
Menu (three dots) > Settings > Privacy & Security > Permissions > Notifications > Set permission for "${window.location.hostname}" to "Allow".`;
break;
case "safari":
instructions = `Enable notification permission in your Safari settings:
Settings > Websites > Notifications > Set permission for "${window.location.hostname}" to "Allow".
For notifications, you must add the site to the Home Screen (Share > Add to Home Screen).`;
break;
case "brave":
instructions = `Turn on notification permission in your Brave settings:
Menu (three dots) > Settings > Privacy and security > Site and Shield Settings > Notifications > Set permission for "${window.location.hostname}" to "Allow".`;
break;
default:
instructions =`Turn on notification permission in your browser settings:
You can usually enable notification permission for "${window.location.hostname}" in Settings > Privacy or Site Permissions.`;
}
const dialog = document.createElement("div");
dialog.id = "permission-denied-prompt";
dialog.style.cssText = `
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
background: linear-gradient(135deg, #ffffff, #f0f4f8);
padding: 30px; border-radius: 12px; box-shadow: 0 8px 16px rgba(0,0,0,0.3);
z-index: 1000; text-align: center; max-width: 450px; width: 95%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
border: 1px solid #e0e0e0;
touch-action: manipulation;
`;
const title = document.createElement("h2");
title.textContent = "Notification Permission Denied";
title.style.cssText = "font-size: 1.5em; font-weight: 600; color: #333; margin-bottom: 15px;";
const message = document.createElement("p");
message.innerHTML = `To allow notifications:
${instructions}`;
message.style.cssText = "font-size: 1.1em; color: #555; margin-bottom: 25px; line-height: 1.4;";
const closeButton = document.createElement("button");
closeButton.id = "close-prompt";
closeButton.textContent = "Close";
closeButton.style.cssText = `
background: #6c757d; color: white; padding: 12px 30px;
border: none; border-radius: 6px; cursor: pointer;
font-size: 1.1em; font-weight: 500; touch-action: manipulation;
`;
dialog.appendChild(title);
dialog.appendChild(message);
dialog.appendChild(closeButton);
document.body.appendChild(dialog);
closeButton.addEventListener("click", () => {
setCookie('bizin', 2, 5); // Reddetme 5 saat hatırlanır
dialog.remove();
});
}
// Bildirim izni için özel pencere gösteren fonksiyon
function showNotificationPrompt() {
const dialog = document.createElement("div");
dialog.id = "notification-prompt";
dialog.style.cssText = `
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
background: linear-gradient(135deg, #fff5e6, #ffe8cc);
padding: 30px; border-radius: 12px; box-shadow: 0 8px 16px rgba(0,0,0,0.3);
z-index: 1000; text-align: center; max-width: 450px; width: 95%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
border: 1px solid #ffca99;
touch-action: manipulation;
`;
// Türkçe karakterler için güvenli metin
const title = document.createElement("h2");
title.textContent = "Opportunities not to be missed!";
title.style.cssText = "font-size: 1.5em; font-weight: 600; color: #333; margin-bottom: 15px;";
const message = document.createElement("p");
message.textContent = "Join Notifications for the best property deals!";
message.style.cssText = "font-size: 1.1em; color: #555; margin-bottom: 25px; line-height: 1.4;";
const icon = document.createElement("span");
icon.textContent = "🏡";
icon.style.cssText = "font-size: 2em; display: block; margin-bottom: 10px;";
const buttonContainer = document.createElement("div");
buttonContainer.style.cssText = "display: flex; justify-content: center; gap: 15px;";
buttonContainer.innerHTML = `
`;
const loadingMessage = document.createElement("p");
loadingMessage.id = "loading-message";
loadingMessage.textContent = "Allowed...";
loadingMessage.style.cssText = "display: none; font-size: 1em; color: #333; margin-top: 15px;";
dialog.appendChild(icon);
dialog.appendChild(title);
dialog.appendChild(message);
dialog.appendChild(buttonContainer);
dialog.appendChild(loadingMessage);
document.body.appendChild(dialog);
const allowButton = document.getElementById("allow-notifications");
const denyButton = document.getElementById("deny-notifications");
// Evet butonuna tıklandığında
allowButton.addEventListener("click", () => {
allowButton.disabled = true;
denyButton.disabled = true;
loadingMessage.style.display = "block";
// Edge mobil ve Android için izin talebini net bir kullanıcı etkileşimiyle tetikle
setTimeout(() => {
requestNotificationPermission();
dialog.remove();
}, 200);
});
// Hayır butonuna tıklandığında
denyButton.addEventListener("click", () => {
dialog.remove();
setCookie('bizin', 2, 5); // Reddetme 5 saat hatırlanır
});
}
// Bildirim izni isteyen fonksiyon
function requestNotificationPermission() {
if ('Notification' in window) {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
// Teşekkür bildirimini yerel olarak gönder
setTimeout(() => {
if ('Notification' in window) {
try {
new Notification("Thanks!", {
body: "You won't miss any discounts and deals! 🎉",
icon: '/varsayilan/res-logo.png',
data: { url: window.location.href },
actions: [{ action: window.location.href, title: "See Deals" }],
requireInteraction: true
});
console.log("Teşekkür bildirimi gönderildi.");
} catch (error) {
console.error("Teşekkür bildirimi gönderme hatası:", error);
}
} else {
console.warn("Bildirim API'si desteklenmiyor.");
}
}, 500); // 500ms gecikme
generateToken();
} else if (permission === "denied") {
if (!sessionStorage.getItem('denied_shown')) {
showPermissionDeniedMessage();
sessionStorage.setItem('denied_shown', '1');
}
}
}).catch((error) => {
console.error("Bildirim izni isteme hatası:", error);
});
} else {
console.warn("Bu tarayıcı bildirimleri desteklemiyor.");
}
}
// FCM token oluşturan fonksiyon
async function generateToken() {
const existingToken = getCookie("fcm_token");
if (existingToken) {
console.log("Mevcut FCM token bulundu:", existingToken);
return;
}
try {
const currentToken = await messaging.getToken({
vapidKey: 'BPH-Nh7LsNzOaGmBX_IW_VWmfHurz7iRlNLKDgO98qYbqdXahKnUtWxOuX034dGvAsY0_cL98lfgIHVIb2iw2ZI'
});
if (currentToken) {
setCookie("fcm_token", currentToken, 5);
console.log("Yeni FCM token oluşturuldu:", currentToken);
var title = document.title.replace(/&/g, 'amp');
var url = document.location.href.replace(/&/g, 'amp');
if (title && url) {
sendTokenToServer(currentToken, title, url);
}
} else {
console.warn("FCM token alınamadı.");
}
} catch (error) {
console.error("Token oluşturma hatası:", error);
}
}
// Token'ı sunucuya gönderen fonksiyon
function sendTokenToServer(token, title, url) {
fetch("/notify.html", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `token=${token}&baslik=${title}&url=${url}`
}).then(() => {
console.log("Token sunucuya gönderildi:", token);
}).catch((error) => {
console.error("Token gönderme hatası:", error);
});
}
// Gelen FCM bildirimlerini işleyen fonksiyon
messaging.onMessage((payload) => {
try {
const notificationData = JSON.parse(payload.data.notification || payload.data.message);
if ('Notification' in window) {
new Notification(notificationData.title, {
icon: '/varsayilan/res-logo.png',
body: notificationData.body,
data: { url: notificationData.click_action || notificationData.data?.url },
actions: [{ action: notificationData.click_action || notificationData.data?.url, title: notificationData.title }],
requireInteraction: true
});
console.log("FCM bildirimi gösterildi:", notificationData.title);
} else {
console.warn("Bildirim API'si desteklenmiyor.");
}
} catch (error) {
console.error("FCM bildirimi işleme hatası:", error);
}
});
// Service Worker hazır olduğunda token oluştur
navigator.serviceWorker.ready.then(() => {
console.log("Service Worker hazır, token oluşturuluyor.");
generateToken();
}).catch((error) => {
console.error("Service Worker hatası:", error);
});
} catch (error) {
console.error("Genel hata:", error);
}
});
// Çerez oluşturma fonksiyonu
function setCookie(name, value, hours) {
let expires = "";
if (hours) {
let date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = `${name}=${value || ""}${expires}; path=/`;
}
// Çerez okuma fonksiyonu
function getCookie(name) {
let nameEQ = `${name}=`;
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}