/**** * Need 3 files, pn.js / sw.js / and manifest file in header. * * Making Live .. change following things * - subscription_api - Path in pn.js * - dataAPI - Path in sw.js file * - Sender Id - manifest file (if its different for live project.) */ var TimesApps = window.TimesApps || {}; var pn_js=(function () { var moduleData = {}, config ={ 'site_logo': '/photo/75555693.cms', 'swjs_path' : '/sw.cms?v=33', 'web_url' : 'http://jeetbetwin.com/etimes', 'web_source' : 'toiweb', 'web_domain' : '.jeetbetwin.com', 'web_subscription_cookie' : '_tointfcsubscriptionid', 'web_fallback_cookie' : '_tointfcsubscribed', 'web_fallback_cookie_value' : 'true', 'web_allow_cookie' : '_tointfcallow', 'web_allow_cookie_value' : 'true', 'web_block_cookie' : '_tointfcblock', 'web_block_cookie_value' : 'true', 'web_ignore_cookie' : '_tointfcskip', 'web_ignore_cookie_value' : 'true', 'wap_url' : 'http://m.timesofindia.com/etimes', 'wap_source' : 'toiwap', 'wap_domain' : '.timesofindia.com', 'wap_subscription_cookie' : '_tointfcsubscriptionid', 'wap_fallback_cookie' : '_tointfcsubscribed', 'wap_fallback_cookie_value' : 'true', 'wap_allow_cookie' : '_tointfcallow', 'wap_allow_cookie_value' : 'true', 'wap_block_cookie' : '_tointfcblock', 'wap_block_cookie_value' : 'true', 'wap_ignore_cookie' : '_tointfcskip', 'wap_ignore_cookie_value' : 'true', 'ntfc_tag' : 'toinews-notification', 'ntfc_subscription_cookie_expiry' : 365, 'ntfc_fallback_cookie_expiry' : 365, 'ntfc_allow_cookie_expiry' : 365, 'ntfc_block_cookie_expiry' : 365, 'ntfc_ignore_cookie_expiry' : 3, 'auto_redirect_timer' : 5, 'redirection_param_enabled' : true, 'ga_enable' : true, 'ga_category' : 'PushBrowserSubscription', 'ga_allow_event' : 'Push_browser_View', 'ga_block_event' : 'Push_browser_View', 'ga_ignore_event' : 'Push_browser_View', 'ga_allow_label' : 'Push_browser_Allow', 'ga_block_label' : 'Push_browser_block', 'ga_ignore_label' : 'Push_browser_cross', 'ga_unregister_event' : 'unregistered', 'ga_autoredirect_event' : 'Auto', 'ga_btn_allow' : 'GotIT_Allow', 'ga_btn_block' : 'GotIT_Block', 'utm_enabled' : true, 'utm_source' : 'browser_notification', 'utm_medium' : '', 'utm_campaign' : 'ETimes_browsernotification', 'subscription_api' : 'http://timesnotifications.jeetbetwin.com/push-notification/subscribe', 'wlcm_ntfc_title' : 'ETimes', 'wlcm_ntfc_msg' : 'Thank you for subscribing to ETimes notifications.', 'safari_pushId': 'web.com.times.push', 'safari_requestUrl': 'http://timesnotifications.jeetbetwin.com/push-notification/safari', 'safari_notification_init': false }; function getSource(){ return (isMobile() === true) ? config.wap_source : config.web_source; } function getBrowser(){ if(/Chrome/i.test(navigator.userAgent)){ return 'chrome'; }else if(/firefox/i.test(navigator.userAgent)){ return 'mozilla'; }else if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){ return 'safari'; } return ''; } function getOs(){ var OSName="Unknown OS"; if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows"; if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS"; if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX"; if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux"; return OSName; } function getAction(act){ return (isMobile() === true) ? act + '_Wap' : act; } function getUrl(){ return (isMobile() === true) ? config.wap_url : config.web_url; } function getRedirectionUrl(action){ var url = getUrl(), ga_action = getAction(action); if(!!document.referrer){ url = document.referrer; } if(action=='wlcm'){ return appendUTMParams(url); }else{ url = appendRedirectionParam(url); } //triggerGAEvent(config.ga_category, ga_action, getBrowser()); return url; } function appendUTMParams(url){ if(!config.utm_enabled) return url; var utm_params = "utm_source="+config.utm_source+"&utm_medium="+((config.utm_medium.length) ? config.utm_medium : getBrowser())+"&utm_campaign="+config.utm_campaign; return url + ((url.indexOf('?')!=-1) ? '&' : '?') + utm_params; } function appendRedirectionParam(url){ if(!config.redirection_param_enabled) return url; return url + ((url.indexOf('?')!=-1) ? '&' : '?')+ config.utm_campaign +"=true"; } function getEndPoint(){ var is_firefox = /firefox/i.test(navigator.userAgent), endpoint = is_firefox ? 'http://updates.push.services.mozilla.com/wpush/v1':'http://fcm.googleapis.com/fcm/send'; return endpoint; } function fetchSubscriptionId(endpoint){ var is_firefox = /firefox/i.test(navigator.userAgent); var strToBeReplaced = is_firefox ? 'http://updates.push.services.mozilla.com/wpush/v1':'http://fcm.googleapis.com/fcm/send'; var subscriptionId = endpoint.replace(strToBeReplaced+"/",""); return subscriptionId; } function isMobile(){ return (function(a) { return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)); })(navigator.userAgent || navigator.vendor || window.opera); } function setCookie(name, value, days, path, domain, secure ) { var expires = ''; days = ( days !== undefined ) ? days : 30; var date = new Date(); date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) ); expires = '; expires=' + date.toGMTString(); domain = ( domain || document.location.host ).split( ":" )[ 0 ]; //removing port path = path || document.location.pathname; //Removing file name, fix for IE11 if( /\/.*\..*/.test( path ) ) { //if path contains file name path = path.split( "/" ); path.pop(); path = path.join( "/" ); } document.cookie = name + '=' + value + expires + ( ( path ) ? ';path=' + path : '' ) + ( ( domain && domain !='localhost' ) ? ';domain=' + domain : '' ) + ( ( secure ) ? ';secure' : '' ); } function getCookie( name ) { var result = name ? undefined : {}; var cookies = document.cookie ? document.cookie.split( '; ' ) : []; for( var i = 0, l = cookies.length; i < l; i++ ) { var parts = cookies[ i ].split( '=' ); var nameK = decodeURIComponent( parts.shift() ); var cookie = parts.join( '=' ); cookie = parseCookieValue( cookie ); if( name && name === nameK ) { result = cookie; break; } if( !name && cookie !== undefined ) { result[ nameK ] = cookie; } } return result; }; function parseCookieValue( s ) { if( s.indexOf( '"' ) === 0 ) { // This is a quoted cookie as according to RFC2068, unescape... s = s.slice( 1, -1 ).replace( /\\"/g, '"' ).replace( /\\\\/g, '\\' ); } try { // If we can't decode the cookie, ignore it, it's unusable. // Replace server-side written pluses with spaces. return decodeURIComponent( s.replace( /\+/g, ' ' ) ); } catch( e ) {} }; function triggerGAEvent(catg, action, label){ if(typeof ga!="undefined" && config.ga_enable){ ga('send', 'event', catg, action, label); } } var GCM_ENDPOINT = getEndPoint(); // This method handles the removal of subscriptionId // in Chrome 44 by concatenating the subscription Id // to the subscription endpoint function endpointWorkaround(pushSubscription) { if (pushSubscription.endpoint.indexOf(GCM_ENDPOINT) !== 0) { return pushSubscription.endpoint; } var mergedEndpoint = pushSubscription.endpoint; // chrome 42 + 43 will not have the subscriptionId attached to the endpoint. if (pushSubscription.subscriptionId && pushSubscription.endpoint.indexOf(pushSubscription.subscriptionId) === -1) { // handle version 42 where you have separate subId and Endpoint mergedEndpoint = pushSubscription.endpoint + '/' + pushSubscription.subscriptionId; } return mergedEndpoint; } function sendSubscriptionToServer(subscription) { var mergedEndpoint = endpointWorkaround(subscription); showCurlCommand(mergedEndpoint); } function showCurlCommand(mergedEndpoint) { if (mergedEndpoint.indexOf(GCM_ENDPOINT) !== 0) { console.log('This browser isn\'t currently ' + 'supported for this demo'); return; } var endpointSections = mergedEndpoint.split('/'); var subscriptionId = endpointSections[endpointSections.length - 1]; try { var dataObj = {}; dataObj.subscribeId = subscriptionId; dataObj.source = getSource(); dataObj.sections = ''; dataObj.browser = getBrowser(); dataObj.cities = ''; // $.post(config.subscription_api, dataObj) // .done(function( data ) { // }); if(isMobile()===true){ setCookie(config.wap_subscription_cookie, subscriptionId , config.ntfc_subscription_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_subscription_cookie, subscriptionId , config.ntfc_subscription_cookie_expiry, "/", config.web_domain, false); } $.ajax({ type: "POST", url: config.subscription_api, data: dataObj, dataType: 'json', cache: false, success: function (result) { if(isMobile()===true){ setCookie(config.wap_fallback_cookie, config.wap_fallback_cookie_value , config.ntfc_fallback_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_fallback_cookie, config.web_fallback_cookie_value , config.ntfc_fallback_cookie_expiry, "/", config.web_domain, false); } }, error:function (error) { console.log("error while subscribing to notification from backend") } }); if(typeof grx != 'undefined'){ grx('profile', 'fcm_token', {fcmId: subscriptionId}); } } catch (ex) { alert("EX" + ex); } } function hitServerApiOnPreviousSubscription(subscriptionId){ try { var dataObj = {}; dataObj.subscribeId = subscriptionId; dataObj.source = getSource(); dataObj.sections = ''; dataObj.browser = getBrowser(); dataObj.cities = ''; if(isMobile()===true){ setCookie(config.wap_subscription_cookie, subscriptionId , config.ntfc_subscription_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_subscription_cookie, subscriptionId , config.ntfc_subscription_cookie_expiry, "/", config.web_domain, false); } $.ajax({ type: "POST", url: config.subscription_api, data: dataObj, dataType: 'json', cache: false, success: function (result) { if(isMobile()===true){ setCookie(config.wap_fallback_cookie, config.wap_fallback_cookie_value , config.ntfc_fallback_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_fallback_cookie, config.web_fallback_cookie_value , config.ntfc_fallback_cookie_expiry, "/", config.web_domain, false); } }, error:function (error) { console.log("error while subscribing to notification from backend") } }); if(typeof grx != 'undefined'){ grx('profile', 'fcm_token', {fcmId: subscriptionId}); } } catch (ex) { alert("EX" + ex); } } function unregisterServiceWorker(type){ //triggerGAEvent(config.ga_category, getAction(config.ga_unregister_event + '_' + type), getBrowser()); var ifrm = document.createElement("iframe"); ifrm.setAttribute("src", "http://timesofindianotifications.jeetbetwin.com/toinotification/unregister.htm"); ifrm.style.width = "1px"; ifrm.style.height = "1px"; ifrm.style.display = "None"; document.body.appendChild(ifrm); }; function unregisterSWPath(path){ navigator.serviceWorker.getRegistrations().then(function(registrations) { for(var registration of registrations) { if (registration.active && typeof registration.active.scriptURL == 'string' && registration.active.scriptURL.indexOf(path) > -1){ registration.unregister(); return true; } } }); }; function subscribe() { navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { serviceWorkerRegistration.pushManager.subscribe({ userVisibleOnly: true }) .then(function(subscription) { if(isMobile()===true){ setCookie(config.wap_allow_cookie, config.wap_allow_cookie_value , config.ntfc_allow_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_allow_cookie, config.web_allow_cookie_value , config.ntfc_allow_cookie_expiry, "/", config.web_domain, false); } triggerGAEvent(config.ga_category, getAction(config.ga_allow_event), config.ga_allow_label); showWelcomeNotification(serviceWorkerRegistration); unregisterServiceWorker('allow'); return sendSubscriptionToServer(subscription); }) .catch(function(e) { if (Notification.permission === 'denied') { if(isMobile()===true){ setCookie(config.wap_block_cookie, config.wap_block_cookie_value , config.ntfc_block_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_block_cookie, config.web_block_cookie_value , config.ntfc_block_cookie_expiry, "/", config.web_domain, false); } triggerGAEvent(config.ga_category, getAction(config.ga_block_event), config.ga_block_label); unregisterServiceWorker('block'); console.log('Permission for Notifications was denied'); } else if (Notification.permission === 'default') { if(isMobile()===true){ setCookie(config.wap_ignore_cookie, config.wap_ignore_cookie_value , config.ntfc_ignore_cookie_expiry, "/", config.wap_domain, false); }else{ setCookie(config.web_ignore_cookie, config.web_ignore_cookie_value , config.ntfc_ignore_cookie_expiry, "/", config.web_domain, false); } triggerGAEvent(config.ga_category, getAction(config.ga_ignore_event), config.ga_ignore_label); } else { console.log('Unable to subscribe to push.', e); } }); }); } function showWelcomeNotification(sw_reg) { try { var notification = sw_reg.showNotification(config.wlcm_ntfc_title, { 'body': config.wlcm_ntfc_msg, 'icon': config.site_logo, 'vibrate': [300, 100, 400], // Vibrate 300ms, pause 100ms, then vibrate 400ms 'tag': config.ntfc_tag, 'data': getRedirectionUrl('wlcm') }); notification.onclick = function (event) { event.target.close(); window.open(event.target.data); return; }; } catch (err) { console.log(err) } } // Once the service worker is registered set the initial state function initialiseState() { if (!('showNotification' in ServiceWorkerRegistration.prototype)) { console.log('Notifications aren\'t supported.'); return; } if (Notification.permission === 'denied') { console.log('The user has blocked notifications.'); return; } // check for push messaging support if (!('PushManager' in window)) { console.log('Push messaging isn\'t supported.'); return; } // service worker registration to check for a subscription navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { serviceWorkerRegistration.pushManager.getSubscription() .then(function(subscription) { if (!subscription) { subscribe(); return; } else{ var subscriptionId = fetchSubscriptionId(subscription.endpoint); hitServerApiOnPreviousSubscription(subscriptionId); } }) .catch(function(err) { console.log('Error during getSubscription()', err); }); }); } function _initPN(){ if ('serviceWorker' in navigator) { // below one is unregister un-necessary wrongly registered service worker path ('/sw/') unregisterSWPath('/sw/'); // check notification cookie if available then dont do anything. // Lets wait for expire. if (getCookie('_tointfcblock') || getCookie('_tointfcallow')){ return; } navigator.serviceWorker.register(config.swjs_path) .then(initialiseState); } } function _subscriptionApiExplicitHit(){ if ('serviceWorker' in navigator) { navigator.serviceWorker.register(config.swjs_path) .then(initialiseState); } } return { init: function(){ _initPN(); }, subscriptionApiExplicitHit : function(){ _subscriptionApiExplicitHit(); } } }());