I'm using a shared worker for a pusher in Laravel, Here XYZABC is my pusher key as string, but is there a way I can use ENV variable or variables defined in my blade file so I don't have to hard-code key there, and also need to switch channels based on country. so is there a way to access java-script variables defined in blade inside a shared worker script? this is my code
This is the sample code from the pusher community I worked on
https://github.com/pusher-community/pusher-with-shared-workers
// Pusher notification works as shared worker thread for providing
// notification across different tab for the same user, thereby reducing
// channel count per user
importScripts("../../common/pusher.worker.min.js");
// An array of the clients/tabs using this worker
var clients = [];
// Connect to Pusher
var pusher = new Pusher("XYZABC", {
encrypted: true,
cluster: 'ap2',
useTLS : true
});
// Log pusher details to console
Pusher.logToConsole = true
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('task-created');
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\TaskCreated', function(data) {
// Relay the message on to each client
clients.forEach(function(client){
client.postMessage(data);
});
});
self.addEventListener("connect", function(evt){
// Add the port to the list of connected clients
var port = evt.ports[0];
clients.push(port);
// Start the worker.
port.start();
});
After few research, found out workers can only communicate using postMessage or onmessage. so passed my key and country details on postMessage after worker start.
PS: Not sure if this is the correct work around or doing anything wrong here, do comment if there is better solution or mistake.
here's my Main thread
here's my modified Worker thread