How to fix importScripts not defined using service worker and onesignal? - ruby-on-rails

I am trying to set up a web push app, with one signal notifications. I know nothing about service workers, but used rails service-workers gem. I get this error >importScripts is not defined.
I have already followed this tutorial from rossta, serviceworker-rails.
The error must be in OneSignalSDKWorker.js.erb.
I have already tried to change the name to OneSignalSDKWorker.js
nothing seems to work. I'm working fully https on Heroku.
make a function
``` funtion(){
importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');
};
```serviceworket-companion.js
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js', { scope: './' })
.then(function(reg) {
console.log('[Companion]', 'Service worker registered!');
});
}
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/OneSignalSDKWorker.js', { scope: './' })
.then(function(reg) {
console.log('[Companion] Onesignal worker registered!');
});
}
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/OneSignalSDKUpdaterWorker.js', { scope: './' })
.then(function(reg) {
console.log('[Companion] Updater worker registered!');
});
}
```
``` OneSignalSDKworker.js.erb
importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');
```
I hope to get user to subscribe in onesignal, but instead it only gives me that error!

I can see a couple potential issues.
1) If you are attempting to importScripts from a service worker, that needs to be executed at the top of the file and not in a method. In other words, it needs to be the first thing that runs within your service worker.
2) You are attempting to register multiple services workers which works but only if they are defined for different scopes. In the code you provided, you are registering them for the same scope which will only register one of them.

Related

What to change to prevent double request from service worker?

Please do not mark as duplicate. This is not an exact duplicate of the other similar questions here on SO. It's more specific and fully reproducible.
Clone this repo.
yarn && yarn dev
Go to localhost:3000 and make sure under (F12)->Applications->Service workers, the service worker is installed.
Go to Network tab and refresh a few times(F5)
Observe how the network requests are doubled.
Example of what I see:
Or if you want to do it manually follow the instructions below:
yarn create-next-app app_name
cd app_name && yarn
in public folder, create file called service-worker.js and paste the following code:
addEventListener("install", (event) => {
self.skipWaiting();
console.log("Service worker installed!");
});
self.addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
const promiseChain = fetch(event.request.clone()); // clone makes no difference
event.waitUntil(promiseChain); // makes no difference
return promiseChain;
})()
);
});
open pages/index.js and just below import Head from "next/head"; paste the following code:
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
window.addEventListener("load", function () {
// there probably needs to be some check if sw is already registered
navigator.serviceWorker
.register("/service-worker.js", { scope: "/" })
.then(function (registration) {
console.log("SW registered: ", registration);
})
.catch(function (registrationError) {
console.log("SW registration failed: ", registrationError);
});
});
}
yarn dev
go to localhost:3000 and make sure the service worker has been loaded under (F12)Applications/Service Workers
Go to the Network tab and refresh the page a few times. See how the service worker sends two requests for each one
What do I need to change in the service-worker.js code so that there are no double requests?
This is how Chrome DevTools shows requests and is expected.
There is a request for a resource from the client JavaScript to the Service Worker and a request from the Service Worker to the server. This will always happen unless the service worker has the response cached and does not need to check the server for an update.
Does not seems the right way to initialize service worker in Next.js.You may need to look into next-pwa plugin to do it right.Here is the tutorial PWA with Next.js
If anyone is looking for an answer to the original question 'What to change to prevent double request from service worker?', specifically for network requests.
I've found a way to prevent it. Use the following in the serviceworker.js. (This also works for api calls etc.)
self.addEventListener('fetch', async function(event) {
await new Promise(function(res){setTimeout(function(){res("fetch request allowed")}, 9999)})
return false
});

Fetch of the service worker doesn't seem to get triggered

When a browser requests an image from the server, the call is getting picked up by an API controller in the back end. There, a authorization check must be done before returning the image in order to check if the request is allowed or not.
So I need to add the authorization header and when searching for the best solution, I found this article: https://www.twelve21.io/how-to-access-images-securely-with-oauth-2-0/ and I was mostly intereseted in the solution number 4 which uses a Service Worker.
I made my own implementation, I registered a serviceWorker:
if ('serviceWorker' in navigator) {
console.log("serviceWorker active");
window.addEventListener('load', onLoad);
}
else {
console.log("serviceWorker not active");
}
function onLoad() {
console.log("onLoad is called");
var scope = {
scope: '/api/imagesgateway/'
};
navigator.serviceWorker.register('/Scripts/ServiceWorker/imageInterceptor.js', scope)
.then(registration => console.log("ServiceWorker registration successful with scope: ", registration.scope))
.catch(error => console.error("ServiceWorker registration failed: ", error));
}
and this is in my imageInterceptor:
self.addEventListener('fetch', event => {
console.log("fetch event triggered");
event.respondWith(
fetch(event.request, {
mode: 'cors',
credentials: 'include',
header: {
'Authorization': 'Bearer ...'
}
})
)
});
When I run my application, I see in my console that the registration seems to be successfully executed as I see the console.logs printed (ServiceWorker active, onLoad is called and successful registration with correct scope: https://localhost:44332/api/imagesgateway/
But when I load an image (https://localhost:44332/api/imagesgateway/...) via the gateway, I still get a 400 and when put a breakpoint on the backend I see that the authentication header is still null. Also, I don't see "fetch event triggered" message in my console. In another article it is stated that I can see the registered service workers via this setting: chrome://inspect/#service-workers but I don't see my worker there either.
My question is: Why isn't the authorization header added? Is it because, although the registration seems to go successfully, this isn't actually the case and therefore I don't see the worker in inspect#service-workers either?
You're not seeing fetch event triggered in the browser console because your Service Worker script isn't allowed to intercept the image requests. This is because your Service Worker script is located in a directory outside the scope of the requests you're interested in.
In order to intercept requests that handle resources at
/api/imagesgateway/
the SW script needs to be located in either
/, /api/, or /api/imagesgateway/. It cannot be located in /some/other/directory/service-worker.js.
This is the reason that your Service Worker registers successfully! There is no probelm in registering the SW. The problem lies in what it can do.
More info: Understanding Service Worker scope

reactjs service worker update

I have a PWA made by create-react-app.
I have service worker enabled as by default.
import registerServiceWorker from './registerServiceWorker'
import App from './App'
ReactDOM.render(
<App />
, document.getElementById('root'))
registerServiceWorker()
On every publish I change package version, but my service-worker doesn't update.
I have tried with function
import { unregister } from './registerServiceWorker';
unregister()
as described here https://github.com/facebook/create-react-app
And this
navigator.serviceWorker.getRegistrations()
.then(registrationsArray => {
if (registrationsArray.length > 0) {
registrationsArray[0].update()
}
})
It doesn't work, what is my mistake? What is wrong?
Thanks
Update to react-scripts ^3.2.0. Verify that you have the new version of serviceWorker.ts or .js. The old one was called registerServiceWorker.ts and the register function did not accept a configuration object. Here is the new one: https://github.com/facebook/create-react-app/blob/3190e4f4a99b8c54acb0993d92fec8a859889a28/packages/cra-template/template/src/serviceWorker.js
Note that this solution only works well if you are Not lazy-loading.
then in index.tsx:
serviceWorker.register({
onUpdate: registration => {
alert('New version available! Ready to update?');
if (registration && registration.waiting) {
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
}
window.location.reload();
}
});
The latest version of the ServiceWorker.ts register()function accepts a config object with a callback function where we can handle upgrading. If we post a message SKIP_WAITING this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh. In this example I am using a javascript alert to inform the user. Please replace this with a custom toast.
The reason this postMessage function works is because under the hood CRA is using workbox-webpack-plugin which includes a SKIP_WAITING listener.
More About Service Workers
good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68
CRA issue discussing service worker cache: https://github.com/facebook/create-react-app/issues/5316
If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox

Should a Service Worker be registered in the manifest or through a script?

Most examples of registering a Service worker do so through JavaScript. For example (From MDN):
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js', {
scope: './'
}).then(function (registration) {
var serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
document.querySelector('#kind').textContent = 'installing';
} else if (registration.waiting) {
serviceWorker = registration.waiting;
document.querySelector('#kind').textContent = 'waiting';
} else if (registration.active) {
serviceWorker = registration.active;
document.querySelector('#kind').textContent = 'active';
}
if (serviceWorker) {
// logState(serviceWorker.state);
serviceWorker.addEventListener('statechange', function (e) {
// logState(e.target.state);
});
}
}).catch (function (error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
});
} else {
// The current browser doesn't support service workers.
}
But I noticed in the Web App Manifest standard that there is a serviceworker member:
"serviceworker": {
"src": "sw.js",
"scope": "/",
"update_via_cache": "none"
}
This is the only place I've seen this referred to.
This raises two questions for me:
1 Which approach SHOULD I use? What are the trade-offs?
The declarative benefit of the manifest approach is obvious, but if I use that approach, how do I reference the registration object in order to track events similar to the script approach? (installing | waiting | active | failed).
Assuming it IS possible to reference the registration object appropriately, can it miss events? Such as finish installing before I could register an event listener to it.
2 What are the caching implications
Since the manifest would be saved in the offline cache, and this manifest would reference the service-worker script, what are the cache implications? Does the 24 hour rule still apply assuming I do NOT store the script in the offline cache? The update_via_cache member is not a simple thing to read in the spec.
It looks like it was added to the spec back in October of 2016, and there is some background discussion in the issue tracker.
My interpretation is that the use case is providing service worker bootstrapping metadata that is relevant when installing a web app via a non-browser mechanism, e.g. via an app store. I don't see any mention of that field in the guidance about Microsoft Store ingestion, though.
So... as of right now, I am not clear that any browsers honor the serviceworker field in the web app manifest, and if your concern is having a functional service worker registration for "browser" use cases, do it using JavaScript.
Your best bet for follow ups would be to ask on the web app manifest's GitHub issue tracker.

How do I use ServiceWorker without a separate JS file?

We create service workers by
navigator.serviceWorker.register('sw.js', { scope: '/' });
We can create new Workers without an external file like this,
var worker = function() { console.log('worker called'); };
var blob = new Blob( [ '(' , worker.toString() , ')()' ], {
type: 'application/javascript'
});
var bloburl = URL.createObjectURL( blob );
var w = new Worker(bloburl);
With the approach of using blob to create ServiceWorkers, we will get a Security Error as the bloburl would be blob:chrome-extension..., and the origin won't be supported by Service Workers.
Is it possible to create a service worker without external file and use the scope as / ?
I would strongly recommend not trying to find a way around the requirement that the service worker implementation code live in a standalone file. There's a very important of the service worker lifecycle, updates, that relies on your browser being able to fetch your registered service worker JavaScript resource periodically and do a byte-for-byte comparison to see if anything has changed.
If something has changed in your service worker code, then the new code will be considered the installing service worker, and the old service worker code will eventually be considered the redundant service worker as soon as all pages that have the old code registered and unloaded/closed.
While a bit difficult to wrap your head around at first, understanding and making use of the different service worker lifecycle states/events are important if you're concerned about cache management. If it weren't for this update logic, once you registered a service worker for a given scope once, it would never give up control, and you'd be stuck if you had a bug in your code/needed to add new functionality.
One hacky way is to use the the same javascript file understand the context and act as a ServiceWorker as well as the one calling it.
HTML
<script src="main.js"></script>
main.js
if(!this.document) {
self.addEventListener('install', function(e) {
console.log('service worker installation');
});
} else {
navigator.serviceWorker.register('main.js')
}
To prevent maintaining this as a big file main.js, we could use,
if(!this.document) {
//service worker js
importScripts('sw.js');
else {
//loadscript document.js by injecting a script tag
}
But it might come back to using a separate sw.js file for service worker to be a better solution. This would be helpful if one'd want a single entry point to the scripts.

Resources