Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Mateus Duarte

NOTIFICAÇÃO NÃO APARECE NO CELULAR

Recommended Posts

Estou com um problema, meu site mostra notificações apenas se for acessado pelo computador. Quando acessado pelo celular, ele pede para ativar as notificações, porem ele não mostra.

 

Codigo da função:

(function(global, factory) {
    "use strict";
    if (typeof define === "function" && define.amd) {
        define(function() {
            return new(factory(global, global.document))
        })
    } else if (typeof module !== "undefined" && module.exports) {
        module.exports = new(factory(global, global.document))
    } else {
        global.Push = new(factory(global, global.document))
    }
})(typeof window !== "undefined" ? window : this, function(w, d) {
    var Push = function() {
        var self = this,
            isUndefined = function(obj) {
                return obj === undefined
            },
            isString = function(obj) {
                return String(obj) === obj
            },
            isFunction = function(obj) {
                return obj && {}.toString.call(obj) === "[object Function]"
            },
            currentId = 0,
            incompatibilityErrorMessage = "PushError: push.js is incompatible with browser.",
            hasPermission = false,
            notifications = {},
            lastWorkerPath = null,
            closeNotification = function(id) {
                var errored = false,
                    notification = notifications[id];
                if (typeof notification !== "undefined") {
                    if (notification.close) {
                        notification.close()
                    } else if (notification.cancel) {
                        notification.cancel()
                    } else if (w.external && w.external.msIsSiteMode) {
                        w.external.msSiteModeClearIconOverlay()
                    } else {
                        errored = true;
                        throw new Error("Unable to close notification: unknown interface")
                    }
                    if (!errored) {
                        return removeNotification(id)
                    }
                }
                return false
            },
            addNotification = function(notification) {
                var id = currentId;
                notifications[id] = notification;
                currentId++;
                return id
            },
            removeNotification = function(id) {
                var dict = {},
                    success = false,
                    key;
                for (key in notifications) {
                    if (notifications.hasOwnProperty(key)) {
                        if (key != id) {
                            dict[key] = notifications[key]
                        } else {
                            success = true
                        }
                    }
                }
                notifications = dict;
                return success
            },
            createCallback = function(title, options) {
                var notification, wrapper, id, onClose;
                options = options || {};
                self.lastWorkerPath = options.serviceWorker || "sw.js";
                if (w.Notification) {
                    try {
                        notification = new w.Notification(title, {
                            icon: isString(options.icon) || isUndefined(options.icon) ? options.icon : options.icon.x32,
                            body: options.body,
                            tag: options.tag,
                            requireInteraction: options.requireInteraction
                        })
                    } catch (e) {
                        if (w.navigator) {
                            w.navigator.serviceWorker.register(options.serviceWorker || "sw.js");
                            w.navigator.serviceWorker.ready.then(function(registration) {
                                registration.showNotification(title, {
                                    body: options.body,
                                    vibrate: options.vibrate,
                                    tag: options.tag,
                                    requireInteraction: options.requireInteraction
                                })
                            })
                        }
                    }
                } else if (w.webkitNotifications) {
                    notification = w.webkitNotifications.createNotification(options.icon, title, options.body);
                    notification.show()
                } else if (navigator.mozNotification) {
                    notification = navigator.mozNotification.createNotification(title, options.body, options.icon);
                    notification.show()
                } else if (w.external && w.external.msIsSiteMode()) {
                    w.external.msSiteModeClearIconOverlay();
                    w.external.msSiteModeSetIconOverlay(isString(options.icon) || isUndefined(options.icon) ? options.icon : options.icon.x16, title);
                    w.external.msSiteModeActivate();
                    notification = {}
                } else {
                    throw new Error("Unable to create notification: unknown interface")
                }
                id = addNotification(notification);
                wrapper = {
                    get: function() {
                        return notification
                    },
                    close: function() {
                        closeNotification(id)
                    }
                };
                if (options.timeout) {
                    setTimeout(function() {
                        wrapper.close()
                    }, options.timeout)
                }
                if (isFunction(options.onShow)) notification.addEventListener("show", options.onShow);
                if (isFunction(options.onError)) notification.addEventListener("error", options.onError);
                if (isFunction(options.onClick)) notification.addEventListener("click", options.onClick);
                onClose = function() {
                    removeNotification(id);
                    if (isFunction(options.onClose)) {
                        options.onClose.call(this)
                    }
                };
                notification.addEventListener("close", onClose);
                notification.addEventListener("cancel", onClose);
                return wrapper
            },
            Permission = {
                DEFAULT: "default",
                GRANTED: "granted",
                DENIED: "denied"
            },
            Permissions = [Permission.GRANTED, Permission.DEFAULT, Permission.DENIED];
        self.Permission = Permission;
        self.Permission.request = function(onGranted, onDenied) {
            if (!self.isSupported) {
                throw new Error(incompatibilityErrorMessage)
            }
            callback = function(result) {
                switch (result) {
                    case self.Permission.GRANTED:
                        hasPermission = true;
                        if (onGranted) onGranted();
                        break;
                    case self.Permission.DENIED:
                        hasPermission = false;
                        if (onDenied) onDenied();
                        break
                }
            };
            if (w.Notification && w.Notification.requestPermission) {
                Notification.requestPermission(callback)
            } else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                w.webkitNotifications.requestPermission(callback)
            } else {
                throw new Error(incompatibilityErrorMessage)
            }
        };
        self.Permission.has = function() {
            return hasPermission
        };
        self.Permission.get = function() {
            var permission;
            if (!self.isSupported) {
                throw new Error(incompatibilityErrorMessage)
            }
            if (w.Notification && w.Notification.permissionLevel) {
                permission = w.Notification.permissionLevel
            } else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                permission = Permissions[w.webkitNotifications.checkPermission()]
            } else if (w.Notification && w.Notification.permission) {
                permission = w.Notification.permission
            } else if (navigator.mozNotification) {
                permission = Permissions.GRANTED
            } else if (w.external && w.external.msIsSiteMode() !== undefined) {
                permission = w.external.msIsSiteMode() ? Permission.GRANTED : Permission.DEFAULT
            } else {
                throw new Error(incompatibilityErrorMessage)
            }
            return permission
        };
        self.isSupported = function() {
            var isSupported = false;
            try {
                isSupported = !!(w.Notification || w.webkitNotifications || navigator.mozNotification || w.external && w.external.msIsSiteMode() !== undefined)
            } catch (e) {}
            return isSupported
        }();
        self.create = function(title, options) {
            if (!self.isSupported) {
                throw new Error(incompatibilityErrorMessage)
            }
            if (!isString(title)) {
                throw new Error("PushError: Title of notification must be a string")
            }
            if (!self.Permission.has()) {
                return new Promise(function(resolve, reject) {
                    self.Permission.request(function() {
                        try {
                            resolve(createCallback(title, options))
                        } catch (e) {
                            reject(e)
                        }
                    }, function() {
                        reject("Permission request declined")
                    })
                })
            } else {
                return new Promise(function(resolve, reject) {
                    try {
                        resolve(createCallback(title, options))
                    } catch (e) {
                        reject(e)
                    }
                })
            }
        };
        self.count = function() {
            var count = 0,
                key;
            for (key in notifications) {
                count++
            }
            return count
        }, self.__lastWorkerPath = function() {
            return self.lastWorkerPath
        }, self.close = function(tag) {
            var key;
            for (key in notifications) {
                notification = notifications[key];
                if (notification.tag === tag) {
                    return closeNotification(key)
                }
            }
        };
        self.clear = function() {
            var i, success = true;
            for (key in notifications) {
                var didClose = closeNotification(key);
                success = success && didClose
            }
            return success
        }
    };
    return Push
});

Como faço para mostrar as notificações pelo celular?

Compartilhar este post


Link para o post
Compartilhar em outros sites

em qual celular vc esta testando?

 

debugando remoto, aparece algum erro?

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
    • Por Giovanird
      Olá a todos!
      Tenho uma pagina que possui uma DIV onde coloquei uma pagina PHP.
      Uso a função setInterval para atualizar a pagina inclusa dentro da DIV.
      O problema é que ao acessar o site , a DIV só me mostra a pagina inclusa somente quando completo o primeiro minuto.
      Preciso que a pagina inclusa já inicie carregada
       
      Meu código JavaScript e a DIV com a pagina PHP
       
      <script> function atualiza(){ var url = 'direita.php'; $.get(url, function(dataReturn) { $('#direita').html(dataReturn); }); } setInterval("atualiza()",60000); </script> <div> <span id="direita"></span> </div>  
    • Por Thiago Duarte
      Oi, gostaria de arrastar imagem e ao soltar formar bloco html, meu bloco de html ficaria com nome, content-1.html, content-2.html, etc
       
      Alguem pode me ajudar?
    • Por belann
      Olá!
       
      Estou fazendo o upload de arquivos com fetch dessa forma
      fetch(url, {
              method: 'POST',
              headers: {'Content-Type': 'multipart/form-data',},
              body: formData 
          }).catch((error) => (console.log("Problemas com o Upload"), error));
       
      estou usando input type=file
      e criando uma const formData = new FormData(); 
      mas não faz e não dá nenhum erro.
      estou fazendo o upload com a url="http://localhost/dashboard/dados".
    • Por joeythai
      Boa tarde pessoal,
       
      Eu criei um formulário em que tenho 3 interações: evento click, change e uma chamada ajax. No evento on change ("select#removal_table_from" )eu faço uma chamada ajax onde eu passo como parametro o id do item selecionado e construo uma tabela dinamica com o próprio javascript, após isto, tenho um input em que o usuario coloca um valor de percentual para que eu possa preencher em 3 colunas da tabela que foi criada dinamicamente: moto_atualizado, carro_atualizado e caminhao_atualizado, até aí tudo bem, o codigo está fazendo isso, porém, como a tabela é criada dinamicamente eu preciso de alguma forma enviar o arrayData para meu backend mas quando faço o calculo dentro do loop apos resposta do meu ajax, os valores desses 3 campos chegam como null, não sei se é possível fazer o que pretendo ou se é ainda não sei como faz
       
      <code>
           $(document).ready(function (event) {   let arrayData = []; let percentage; let removal_vehicle; let removal_motorcycle; let removal_tuck; let apply_removal = $('#apply_removal');   // apply_removal.on('click', function () { // percentage = $('#percentage').val();   // $('.table-body tr').each(function () {   // let veiculo = $(this).find('.veiculo').text(); // let moto = $(this).find('.moto').text(); // let caminhao = $(this).find('.caminhao').text();   // let removal_vehicle = parseFloat(veiculo) + (parseFloat(veiculo) * parseFloat(percentage)) / 100; // let removal_motorcycle = parseFloat(moto) + (parseFloat(moto) * parseFloat(percentage)) / 100; // let removal_tuck = parseFloat(caminhao) + (parseFloat(caminhao) * parseFloat(percentage)) / 100;   // arrayData.push({ // removal_vehicle, // removal_motorcycle, // removal_tuck // })   // $(this).find('.veiculo_atualizado').val(removal_vehicle.toFixed(2)); // $(this).find('.moto_atualizado').val(removal_motorcycle.toFixed(2)); // $(this).find('.caminhao_atualizado').val(removal_tuck.toFixed(2)); // }); // });   apply_removal.on('click', function () { percentage = $('#percentage').val();   $('.table-body tr').each(function () {   let veiculo = $(this).find('.veiculo').text(); let moto = $(this).find('.moto').text(); let caminhao = $(this).find('.caminhao').text();   removal_vehicle = parseFloat(veiculo) + (parseFloat(veiculo) * parseFloat(percentage)) / 100; removal_motorcycle = parseFloat(moto) + (parseFloat(moto) * parseFloat(percentage)) / 100; removal_tuck = parseFloat(caminhao) + (parseFloat(caminhao) * parseFloat(percentage)) / 100;   arrayData.push({ removal_vehicle, removal_motorcycle, removal_tuck })   $(this).find('.veiculo_atualizado').val(removal_vehicle.toFixed(2)); $(this).find('.moto_atualizado').val(removal_motorcycle.toFixed(2)); $(this).find('.caminhao_atualizado').val(removal_tuck.toFixed(2));     console.log('Removal Vehicle:', removal_vehicle); console.log('Removal Motorcycle:', removal_motorcycle); console.log('Removal Truck:', removal_tuck); }); });   $('select#removal_table_from').on('change', function (e) { let table_id = $(this).val(); let action = route('removal.removal-values.show', table_id);   $.ajax({ type: "GET", url: action, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },   success: function (data) { $('.table-body').empty();   for (let i = 0; i < data.length; i++) { let carro = parseFloat(data[i].CARRO); let moto = parseFloat(data[i].MOTO); let caminhao = parseFloat(data[i].CAMINHAO); let distancia = data[i].DISTANCIA; let origem = data[i].ORIGEM; let destino = data[i].DESTINO; let localidadeOrigem = data[i].LocalidadeOrigem_ID; let localidadeDestino = data[i].LocalidadeDestino_ID;   let newRow = '<tr class="removal-row">' + '<td class="align-middle">' + '<div class="row">' + '<div class="col-1">' + '<span class="font-weight-bold">Origem</span><br>' + '<span class="origem">' + origem + '</span>' + '</div>' + '<div class="col-1">' + '<span class="font-weight-bold">Destino</span><br>' + '<span class="destino">' + destino + '</span>' + '</div>' + '<div class="col-1">' + '<span class="font-weight-bold">KM</span><br>' + '<span class="km">' + distancia + '</span>' + '</div>' + '<div class="col-1">' + '<span class="font-weight-bold">Veículo</span><br>' + '<span class="veiculo">' + carro + '</span>' + '</div>' + '<div class="col-2">' + '<span class="font-weight-bold">Veículo Atualizado</span><br>' + '<input type="text" class="veiculo_atualizado">' + '</div>' + '<div class="col-1">' + '<span class="font-weight-bold">Moto</span><br>' + '<span class="moto">' + moto + '</span>' + '</div>' + '<div class="col-2">' + '<span class="font-weight-bold">Moto Atualizado</span><br>' + '<input type="text" class="moto_atualizado">' + '</div>' + '<div class="col-1">' + '<span class="font-weight-bold">Caminhão</span><br>' + '<span class="caminhao">' + caminhao + '</span>' + '</div>' + '<div class="col-2">' + '<span class="font-weight-bold">Caminhão Atualizado</span><br>' + '<input type="text" class="caminhao_atualizado">' + '</div>' + '</div>' + '</div>' + '</td>' + '</tr>';   $('.table-body').append(newRow); //let row = $('.removal-row:last');   // Calcula o valor atualizado e define nos campos diretamente // let veiculo_atualizado = carro + (carro * percentage) / 100; // let moto_atualizado = moto + (moto * percentage) / 100; // let caminhao_atualizado = caminhao + (caminhao * percentage) / 100; // console.log('PORCENTS: ', percentage); //console.log('Veiculo Atualizado:', veiculo_atualizado, 'Moto Atualizado:', moto_atualizado, 'Caminhao Atualizado:', caminhao_atualizado);   // Define os valores diretamente nos campos da nova linha // row.find('.veiculo_atualizado').val(veiculo_atualizado.toFixed(2)); // row.find('.moto_atualizado').val(moto_atualizado.toFixed(2)); // row.find('.caminhao_atualizado').val(caminhao_atualizado.toFixed(2));   arrayData.push({ carro, moto, caminhao, distancia, origem, destino, localidadeOrigem, localidadeDestino, removal_vehicle, removal_motorcycle, removal_tuck }); }   $('#copy_data_table').val(JSON.stringify(arrayData)); }   }); });   //javascript para o formulario de cadastro // $(document).ready(function (event) { $('#uf').change(function () { let code_city = $(this).val(); let deposit = localStorage.getItem('selected_deposit_id'); let action = route('removal.removal-values.cities', code_city); $.ajax({ type: "POST", url: action, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { code_city: code_city },   success: function (data) {   $('#city').empty(); $('#deposit').empty();   for (let i = 0; i < data.cities.length; i++) { $('#city').append('<option value="' + data.cities[i].NM + '">' + data.cities[i].NM + '<option>'); }   if (data.deposits.length > 0) { for (let i = 0; i < data.deposits.length; i++) { $('#deposit').append('<option value="' + data.deposits[i].NM + '">' + data.deposits[i].NM + '<option>'); } } else { // $('#deposit').prop('disabled', true); // $('#city').prop('disabled', false); }   $('#city').trigger('change'); } });   });   $('#deposit').on('change', function () { depositId = $(this).val(); localStorage.setItem('selected_deposit_id', depositId); });   $('#uf_destiny').change(function () { let code_city = $(this).val(); let depositDestiny = localStorage.getItem('selected_deposit_destiny_id'); let action = route('removal.removal-values.cities', code_city); $.ajax({ type: "POST", url: action, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { code_city: code_city },   success: function (data) {   $('#city_destiny').empty(); $('#deposit_destiny').empty();   for (let i = 0; i < data.cities.length; i++) { $('#city_destiny').append('<option value="' + data.cities[i].NM + '">' + data.cities[i].NM + '</option>'); }   if (data.deposits.length > 0) { // $('#deposit_destiny').prop('disabled', false); //$('#city_destiny').empty(); // $('#city_destiny').prop('disabled', true); for (let i = 0; i < data.deposits.length; i++) { $('#deposit_destiny').append('<option value="' + data.deposits[i].NM + '">' + data.deposits[i].NM + '</option>'); } } else { // $('#deposit_destiny').prop('disabled', true); // $('#city_destiny').prop('disabled', false); }   $('#city_destiny').trigger('change'); } }); });   $('#deposit_destiny').on('change', function () { let depositDestinyId = $(this).val(); localStorage.setItem('selected_deposit_destiny_id', depositDestinyId); });   }); </code>
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.