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.
Related
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.
I have a short question.
Does inertia render asynch?
I realized, as soon I delete a DB - Entry, while I connect to new Nav-Link direct afterwards (Inertia.onStart)- which redirects me on another Page, the changes (onSuccess) wont be showed up.
Inertia.post('data-delete', {
id: this.meeeh.data[index].id,
}, {
preserveScroll: true,
onBefore: () => {
window.Toast.confirm('Delete?');
},
onStart: (visit) => {
window.Toast.load('Delete...');
},
onSuccess: (page) => {
return Promise.all([
window.Toast.success(page.props.toast),
/** Wont show after click another Link in Navbar */
])
},
onError: (errors) => {
window.Toast.error(errors);
}
});
How does it come, I have to wait until the process is Finished - otherwise my Page is not working correctly?
Not sure if I understand what you're looking for.
onSuccess runs immediately after the post request has finished AND in successful. It is completely separated from other links and it's purpose (if your returning a Promise from it) is to delay the execution of the onFinish handler.
From the docs:
It's also possible to return a promise from the onSuccess() and
onError() callbacks. This will delay the "finish" event until the
promise has resolved.
I also believe there's some problem in your code: Promise.all should receive an array os Promises and I'm pretty sure window.Toast.success(page.props.toast) isn't returning one, is it?
So... chances are that your Promise.all is never resolving.
I have an existing Express ApolloServer . I added subscription to that . I can see when I fire the subscription from Playground, the resolve method is called . But, the subscribe method is never called
const { PubSub, withFilter } = require ('apollo-server');
const pubsub = new PubSub();
const SOMETHING_CHANGED_TOPIC = 'something_changed';
const mySubscription = {
Subscription: {
somethingChanged: {
resolve: root => {
console.log('subscription server resolve', { root })
return root
},
subscribe: () => {
console.log('I AM HERE IN SUBSCRIPTION', pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC))
return pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC)
}
}
}
};
module.exports = { mySubscription}
I can see the console.log('subscription server resolve', { root }) getting printed although root is undefined. But the similar console.log('````') in subscribe is not executed .
You need to call pubsub.publish somewhere (usually in one of your resolvers) to trigger the subscription.
https://www.apollographql.com/docs/apollo-server/data/subscriptions/#subscriptions-example
I had a similar issue, there were a couple things I needed to achieve to accomplish this.
I had to remove my resolve() function to get it working. For some reason, having the resolve() function defined caused my subscription not to work.
I also had failed to follow the
https://www.apollographql.com/docs/react/data/subscriptions/#setting-up-the-transport. I was trying to request my subscription over the http link instead of over a ws link.
In general, a good test to see where the issue lies is to try to subscribe to your message using the GraphQL sandbox at http://localhost:4000/graphql (or wherever your sandbox is setup to run at when you start your server). If the sandbox subscribes successfully, the issue lies in your client code. If the sandbox fails to subscribe, the issue lies in your server code.
Please let me know if you are still having the issue and I will try to help.
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
I am going to test backend server running with Jest.
It success sometimes, but other times it shows error like this.
So if I use --detectOpenHandles flag as suggested, It always success without showing eny error.
This is test code.
it("should be able to initialize a server (development)",async (done) => {
// Before main() is called there is no active connection:
expect(connection.readyState).toBe(0);
return main({
env: "dev",
port: PORT,
})
.then(async (server: ApolloServer) => {
// After main() got called, there is an active connection:
expect(connection.readyState).toBe(1);
await server.stop();
done();
})
});
afterAll(async () => {
await connection.close(); //connection is mongoose.connection
});
I am not sure why it fails when flag.
And it weird it sometimes success, and other times fails.
Thanks
I faced a similar issue and managed to resolve it by returning a promise in the function passed to afterAll. For example:
afterAll(() => {
return connection.close(); // connection.close() returns a promise
});
Docs for reference
Not related to the user's question, but causes the problem in the title nevertheless:
Switching from
testEnvironment: 'node', to testEnvironment: 'jsdom', in jest.config.js seemed to fix the issue.