I'm trying to add push messaging to my service worker and facing issue that is eluding me since last night.
In my main HTML file, I have the following -
<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js', {scope: '/pwa/'}).then(registration => {
console.log('Service Worker Registered: ', registration);
registration.pushManager.subscribe({userVisibleOnly:true});
});
})
}
</script>
I do get "Service Worker Registered" message on the console. Which means the registration is successful. Chrome however follows it with following line that doesn't say anything about the error -
Uncaught (in promise) DOMException (index):1
Clicking on the (index):1 takes me to the top of corresponding page /pwa/, and highlights the <!DOCTYPE html>.
It does not give me any meaningful information to investigate the issue further.
Would appreciate if you could guide me in fixing this issue. I'll paste the rest of my code and setup below.
Backend framework: Laravel.
Entry in my webpack.mix.js
const workboxPlugin = require('workbox-webpack-plugin');
mix.webpackConfig({
plugins: [
new workboxPlugin.InjectManifest({
swSrc: 'public/service-worker-offline.js', // more control over the caching
swDest: 'service-worker.js', // the service-worker file name
importsDirectory: 'service-worker-assets' // have a dedicated folder for sw files
})
],
output: {
publicPath: '' // Refer: https://github.com/GoogleChrome/workbox/issues/1534
}
});
Entry in my service-worker-offline.js -
workbox.skipWaiting();
workbox.clientsClaim();
// some other entries, followed by
self.addEventListener('push', (event) => {
const title = 'Aha! Push Notifications with Service Worker';
const options = {
'body' : event.data.text()
};
event.waitUntil(self.registration.showNotification(title, options))
});
I look forward to your responses and thank you in advance for your help.
Addendum:
I did further investigation and found out that if I do -
Notification.requestPermission().then(function(permission) {
registration.pushManager.subscribe({userVisibleOnly: true});
})
then the push notification works; but the error still remains. However, the error now points to registration.pushManager.subscribe({userVisibleOnly: true}); line in the JS. What could be the reason?
The DOMException has details that are not always visible. Catch your DOMException, and make sure to log the message to the console. It will generally be much more informative. In my case, the "Registration failed - permission denied" message reminded me that I had blocked all notifications in my chrome settings.
If you are using react, fix serviceWorker.unregister () with serviceWorker.register () in index.js. I solved it like this
Related
I am trying to test my website from cypress.io, but i am constantly getting above error.
I am facing issue will Signing in with google. I am using the cy.origin() method.
/// <reference types="cypress" />
describe('Basic tests', () => {
it.only('Login should happen', ()=>{
// cy.viewport(1280, 720)
cy.visit('https://internetcomputerservices.com')
cy.contains('Dashboard').click()
cy.contains('Sign in with Google').click()
cy.origin('https://accounts.google.com/o/oauth2/auth', ()=>{
cy.get('[aria-label="Email or phone"]').click().type('haswrfbi20#gmail.com')
});
})
})
Please help me
Although I haven't able to find the solution for testing google login, i have connected with team and they will most likely resolve this issue in cypress 10.10.0.
For meanwhile, you can use token to directly login, by-pass the google-login and test the website.
you can find the token by going to developer tools and there you will find Application, click on it, there you will find the token, copy it and paste it in below code.
Make sure to install the package before hand:
npm i cypress-localstorage-commands
Code:
describe("Basic tests", () => {
before(() => {
cy.visit("---your-website-url---", {
onBeforeLoad(win) {
win.localStorage.setItem(
"token",
"---token-here---"
);
},
});
});
it.only("should be able to run test 1", async () => {
// write your first test here ----
});
});
I'm trying to make socket.io-client work in a svelte front end app to talk to an existing API server that already uses socket.io. After a number of challenges, I managed to make this work but I can only get this to work with sveltekit's preview and not in dev mode. Wondered if someone with some knowledge of those could explain why or suggest what I need to do to get it connecting in dev?
svelte 3.34.0
sveltekit next-169
socket.io(-client) 4.2.0
basic code as follows, currently within a file $lib/db.js where I define a few stores that are pulled into the layout for general use..
import { io } from "socket.io-client";
import { browser } from '$app/env';
const initSocket = async () => {
console.log('creating socket...');
let socket = io('http://192.168.1.5:4000', { 'connect timeout': 5000 });
socket.on("connect", () => {
// always works in preview...
console.log('socket created with ID:', socket.id);
});
socket.on("connect_error", (error) => {
// permanently fired in dev...
console.error('Failed to connect', error);
});
socket.on("error", (error) => {
console.error('Error on socket', error);
});
socket.on("foo", data => {
// works in preview when server emits a message of type 'foo'..
console.log("FOO:", data);
});
};
if (browser) {
initSocket();
}
// stores setup and exports omitted..
with svelte-kit preview --host I see the socket creation log message with the socket ID and the same can be seen on the api server where it logs the same ID. The socket works and data is received as expected.
with svelte-kit dev --host however, the log message from socket.on("connect").. is never output and I just see an endless stream of error messages in the browser console from the socket.on("connect_error").. call..
Failed to connect Error: xhr poll error
at XHR.onError (transport.js:31)
at Request.<anonymous> (polling-xhr.js:93)
at Request.Emitter.emit (index.js:145)
at Request.onError (polling-xhr.js:242)
at polling-xhr.js:205
Importantly, there is no attempt to actually contact the server at all. The server never receives a connection request and wireshark/tcpdump confirm that no packet is ever transmitted to 192.168.1.5:4000
Obviously having to rebuild and re-run preview mode on each code change makes development pretty painful, does anyone have insight as to what the issue is here or suggestions on how to proceed?
I've had a similar problem, I solved it by adding this code to svelte.config.js:
const config = {
kit: {
vite: {
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js",
},
},
},
},
};
The solution was provided by this comment from the vite issues.
We're trying to get some events/messages to post when a user exits a chatbot window (or the site) (or a welcome message), but so far the events are not firing.
I can see within Inspector tools:
Screen Shot 2020-02-18 at 3 15 39 PM
Various activities/conversations are created, the chatbot works, but no welcome/exit events are triggered.
The code we're using is nearly if not identical to documentation code here: https://github.com/microsoft/BotFramework-WebChat/blob/master/docs/WELCOME_MESSAGE.md
and here: How to handle user leaving conversation
I have a function that fires when the window is closed, as follows:
const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => async action => {
return next( action );});
window.addEventListener( 'sendEventActivity', ( { data } ) => {
store.dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'user_event',
value: {
name: 'end_conversation',
value: 'user ended conversation'
},
text: 'The user has left the conversation.'
}
})
});
function exitEvent(){
const eventSendActivity = new Event( 'sendEventActivity' );
eventSendActivity.data = 'User left conversation';
window.dispatchEvent( eventSendActivity );
console.log('Exit Event Submitted (hopefully)');
}
exitEvent();
I have tried other variations, defining the store earlier, above render chat, after render chat, sending welcome messages from various locations and at various times but can't seem to get it to send.
We are using https://cdn.botframework.com/botframework-webchat/latest/webchat.js
Any idea what the issue might be? Not sure where we are going wrong or why it's not firing - copying in theory known to be working code straight into our code doesn't seem to do the trick.
Thanks in advance and please let me know if I have failed to include any necessary details- new to chatbot and do not post much on github. Many thanks,
EDIT:
I was able to marry the aforementioned code and code from here: https://github.com/microsoft/BotFramework-WebChat/issues/2120#issuecomment-516056614 in order to achieve what I wanted. I'll post below in case it helps anyone else...
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join'
}
});
}
return next(action);
});
window.addEventListener( 'sendEventActivity', ( { data } ) => {
store.dispatch( {
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/exit'
}
} );
} );
document.getElementById("action_menu_btn").addEventListener( 'click', function() {
const eventSendActivity = new Event( 'sendEventActivity' );
eventSendActivity.data = 'User left conversation';
window.dispatchEvent( eventSendActivity );
console.log('End Converstaion Event Fired');
});
Cheers!
I failed to mention this in the other post (I'll update it), but the reason the code works is because of the window.onbeforeunload() function. Without it, the window closes before any code can finish executing. The result being no event is created, is caught by a listener, nor is sent via the Web Chat store to the bot.
Here, using the above, refreshing the page produces the "User left conversation" activity.
Also, something to note, any function you create and pass thru like you have with exitEvent() is going to run as soon as the page loads. Take the following code which gets the user's location via the browser (placed just before the closing </script> tag). As you can see, it's loading even before Web Chat. If you are wanting a function to run according to some activity passed from the bot, then utilize either the store's actions (i.e. DIRECT_LINE/INCOMING_ACTIVITY, or some other) or via the available middleware.
let geoLoc = async () => {
await navigator.geolocation.getCurrentPosition(position => {
console.log('Latitude: ', position.coords.latitude);
console.log('Longitude: ', position.coords.longitude);
});
}
geoLoc();
Regarding a welcome message, you have two options. Either send as an activity from your bot (reference this sample) or initiate an event on your page after some initial activity is received (reference this sample).
Lastly, I would recommend getting the code working as-is before tinkering with it. This usually trips me up, so thought I'd pass it along.
Hope of help!
I am following this very clear tutorial.
All works except that when I get to the stage subscribing a user with pushManager when I call pushManager.subscribe() I don't get any response from the promise whose status is pending.
Maybe I am missing some glaring problem with my setup, which is as follows:
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('service-worker.js')
.then(function(swReg) {
console.log('Service worker successfully registered.');
navigator.serviceWorker.ready.then(function() {
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: ... // My application server key.
};
let promise = swReg.pushManager.subscribe(subscribeOptions)
console.log(promise) // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
promise
.then(function(pushSubscription) {
console.log('Received PushSubscription: ', pushSubscription); // Never gets called.
})
.catch(function(err) {
console.error('Unable to subscribe.', err); // Never gets called.
});
})
})
.catch(function(err) {
console.error('Unable to register service worker.', err);
});
}
Should additional configuration be made somewhere else? Any advice is appreciated.
Just came across this thread.
The advice is to delete the GCM Store directory located in:
C:\Users\[username]\AppData\Local\Google\Chrome\User Data\Default\GCM Store
I first had to quit Chrome, delete the folder and then re-launch to get it to work.
Seems like a bug which is traceable back to June 2016 (Chrome 51) and even though it is now October 2017 (Chrome 61) it still seems to be an issue.
Hope this may help somebody.
Error: The connection to <websocket> was interrupted while the page was loading.
Source File: localhost/socket.io/node_modules/socket.io-client/dist/socket.io.js
Line: 2371
I am new to socket.io and I have tried to search for this, but I didn't get an answer.
Websocket is interrupted when I refresh page on Firefox. That's why server side is waiting to authorise client.
Here is code:
server.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs')
app.listen(8080);
function handler(req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
//alert(JSON.stringify(data));
console.log(data);
});
});
index.html
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
</script>
It happens because, you are not closing your open websocket.
This code would remove this error:
$(window).on('beforeunload', function(){
socket.close();
});
This seems to be an open bug in Firefox (as of 2015-03-29):
https://bugzilla.mozilla.org/show_bug.cgi?id=712329
The workaround (for now) is to call close() on the websocket on beforeunload, as Alexander pointed out.
Update 2016-04: According to Bugzilla, this will be fixed in Firefox 48
I was just running through the Socket.IO tutorials and I ran into this exact problem. I tried the posted solutions but they didn't seem to work at all.
After some fiddling and some screaming and some rubber-ducking, I finally figured out what the issue was. The issue is that it's trying to connect to the socket before the socket variables have been properly initialized. Javascript boo boo #1.
If you will ammend your file to include jQuery and then wrap your functions like so:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
});
</script>
You will have much more success.
What impact does this have on your application? My guess is that it's just not great to see an error in the console.
The problem here is that you are seeing Firefox loggin this error and there's nothing you can do about it. It's not possible to capture this error with a try...catch block or via websocket.onerror/websocket.onclose.
See: How do I catch a WebSocket connection interruption?
Related:
Should WebSocket.onclose be triggered by user navigation or refresh?
Firefox - Race condition allows ghost WebSocket connections to live after tab closed
I've had this problem with our custom Undertow-based webserver for years -- my problem was that my server was not responding to the socket close message.
Based on a comment by Jan Wielemaker I checked my socket close handler code for AbstractReceiveListener.onFullCloseMessage and realized I had not called the super method. After adding super.close() the socket closes cleanly on the client and no error is emitted.
One solution is to put a timeout on the disconnect event.
setTimeout(() => {
$('#offlineModal').modal('show')
}, 5000)