Why do I get `ReferenceError: Can’t find variable: picobel`?

I am building a webpage with an audio player:

...
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

I want to replace it with this fancy player called Picobel.

The documentation says I can use it the old-fashioned way:

<!-- Load Picobel -->
<script type='text/javascript' src='picobel.min.js'></script>
<script type='text/javascript'>
    picobel();
</script>

Only it’s an NPM package and I’m not sure where to find picobel.min.js

There is a file called ode_modules/picobel/legacy/picobel.legacy.min.js

But when I point my webpage to that I get the error ReferenceError: Can't find variable: picobel.

How do I use Picobel without resorting to Yarn/NPM?

unit test class with playwright

I have a setup where I can do unit tests with playwright. The setup is (just the important files)

~/folder: ls
sum.js
tests/foo.spec.js

sum.js

function sum(a, b) {
  return a + b*2;
}

foo.spec.js

const { test, expect } = require('@playwright/test');

test.describe('simple suite test', () => {
    test('unit test sum.js function', async ({ page }) => {

        await page.addScriptTag({path: 'sum.js'});
        const data = await page.evaluate(() => window.sum(1,7));
        await expect(data).toBe(15); // 1+7*2=15
        
    });
 });

The test is executed through npx playwright test foo.spec.js --project chromium.

Now I wanted to call a class function, but I do not know how to do it? Somehow I have to create the object and call the function. But how?

sum.js (updated)

class Calc {
    add(a,b) {
        return a + b*3;
    }
}

foo.spec.js (updated)

const { test, expect } = require('@playwright/test');

test.describe('simple suite test', () => {
    test('unit test sum.js function', async ({ page }) => {

        await page.addScriptTag({path: 'sum.js'});
        const data = await page.evaluate(() => window.object.add(1,7));  // <- how to call the class function?
        await expect(data).toBe(22); // 1+7*3=22
        
    });
 });

HTML Form not validating inside a dialog box

It is a typical HTML form with textboxes. I am looking for the client side validation you get with forms but it’s not happening. I’m sure I did something wrong but I don’t know what it is. I am expecting real time validation on my ‘required’ textbox elements.

Right now I have two buttons, one to open the dialog box and one button to close it.

I’d like to do something with the data being submitted but I need the form validation to happen first so I haven’t written out any logic for that yet.

EDIT: I don’t know if you always had to do this but I added two CSS properties and it did work so, is this how it always needs to be? This is what I added to my CSS file

input:invalid {
border: 2px solid red;
}

input:valid {
border: 2px solid black;
}

const modal = document.querySelector('.modal');
const openModal = document.querySelector('.open-button');
const closeModal = document.querySelector('.close-button');

openModal.addEventListener('click', () => {
  modal.showModal();
});

closeModal.addEventListener('click', () => {
  modal.close();
})
modal::backdrop {
  background: rgb(0 0 0 / .4);
}

.modal {
  padding: 1em;
  max-width: 50ch;
}

body {
  background-color: rgb(215, 137, 28);
}

dialog label {
  font-size: 18px;
}

dialog h2 {
  margin-top: 10px;
}

dialog text {
  width: 100%;
}

dialog input:nth-of-type(3) {
  margin-bottom: 20px;
}

.close-button {
  margin-bottom: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h2>An interesting title</h2>
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Amet maiores placeat dolorum corporis nihil sapiente cupiditate animi rem ab tenetur facilis ad hic corrupti eligendi, nulla labore, impedit eveniet repudiandae!</p>

  <button class="button open-button">open modal</button>

  <dialog class="modal" id="modal">
    <h2>An interesting title</h2>
    <form class="form" method="dialog">
      <label>Book Title </label><br><input type="text" required /><br>
      <label>Author </label><br><input id="author" type="text" required /><br>
      <label>Number of pages </label><br><input id="pages" type="text" required /><br>
    </form>
    <button class="button close-button">close modal</button>
  </dialog>
  <script type="module" src="index.js"></script>
</body>
</html>

trying to send multipart data

I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty
This is how I am sending data using api
Add a new cafe using multipart/form-data

  const api = createAuthAxios()

  try {
    // Ensure 'form' is a FormData object
    if (!(form instanceof FormData)) {
      throw new Error('Form data must be a FormData object.')
    }

    const response = await api.post('/cafes', form)
    return response.data // Return the response data directly
  } catch (error) {
    console.error('Error adding cafe:', error)
    throw error // Rethrow error to handle it in the calling function
  }
}```

this is my axis setup from where I am trying to create a custom header for the form-data 

```const createAuthAxios = () => {
  const token = localStorage.getItem('bearerToken')

  if (!token) {
    na
    console.error('No bearer token found')
    throw new Error('Bearer token is missing') // Throw error to handle token absence
  }

  return axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // Ensure VITE_API_BASE_URL is properly set in the env files
    headers: {
      Authorization: `Bearer ${token}`, // Use the token in the Authorization header
    },
  })
}```

this is my design for react this is how I am creating form data but the problem is it is sending I wanted to send the image array and form in react but my problem is it is showing the data in payload but when I debug in backend its body is empty this error. 

"Cannot convert object to primitive value"
 this is the error that is being responded and it is completely working on postman


 

const { register, handleSubmit, setValue, getValues, reset, control } = useForm({
defaultValues: {
name: ”,
location: {
address: {
street: ”,
suburb: ”,
state: ”,
postalCode: ”,
},
},
managedBy: ”,
timetable: [
{ day: ‘Monday’, openingTime: ”, closingTime: ” },
{ day: ‘Tuesday’, openingTime: ”, closingTime: ” },
{ day: ‘Wednesday’, openingTime: ”, closingTime: ” },
{ day: ‘Thursday’, openingTime: ”, closingTime: ” },
{ day: ‘Friday’, openingTime: ”, closingTime: ” },
{ day: ‘Saturday’, openingTime: ”, closingTime: ” },
{ day: ‘Sunday’, openingTime: ”, closingTime: ” },
],
images: [],
},
})

const { fields } = useFieldArray({
control,
name: ‘timetable’,
})

const [imagePreviews, setImagePreviews] = useState([])
const [users, setUsers] = useState([])

const submitForm = async (data) => {
try {
// Create FormData object
const formData = new FormData()

  // Append basic fields to FormData
  formData.append('name', data.name)
  formData.append('location[address][street]', data.location.address.street)
  formData.append('location[address][suburb]', data.location.address.suburb)
  formData.append('location[address][state]', data.location.address.state)
  formData.append('location[address][postalCode]', data.location.address.postalCode)
  formData.append('managedBy', data.managedBy)

  // Append timetable fields to FormData
  data.timetable.forEach((timetableItem, index) => {
    formData.append(`timetable[${index}][day]`, timetableItem.day)
    formData.append(`timetable[${index}][openingTime]`, timetableItem.openingTime)
    formData.append(`timetable[${index}][closingTime]`, timetableItem.closingTime)
  })

  // Append images (files) to FormData
  data.images.forEach((file) => {
    formData.append('images', file)
  })

  // Send FormData to the API
  const response = await add_cafe(formData)
  console.log('Cafe added successfully:', response.data)

  // Reset the form and clear previews on success
  reset()
  setImagePreviews([])
} catch (error) {
  console.error('Error submitting cafe:', error)
}

}


How do i implement audio group call functionality using WebRTC, Socket.IO and Node.js in my CRA project?

I’m looking to implement a feature in my application that lets users make audio group calls over the internet using socket.io, WebRTC and a Node.js server. I am currently using this library called simple-peer to connect between multiple peers and the connection from the client part (a react webpage in the browser) to the server (a node.js server running socket.io and express) is working fine as expeted, but transmitting audio seems to be failing for some reason.

For starters, i’m using node version 18.17.1, npm version 9.6.7 and the version of simple-peer and socket.io-client versions specified in my package.json are:

"socket.io-client": "^4.8.1", 
"simple-peer": "^9.11.1"   

Ive imported the two libaries into my App.js class file (im using Component instead of function) like so:

import io from 'socket.io-client';
import SimplePeer from "simple-peer";

...

class App extends Component {...

Then in my state, ive declared three state variables like so:

state={
    myId:'',
    roomId:'',
    peers:[]
}

The roomId variable is used when establishing a new room thats meant to contain all the connected users subscribed or listening in to that specific room and peers is meant to contain instantiated SimplePeer objects. Then, i have a constructor to hold some refs:

constructor(props) {
    super(props);
    this.localStream = React.createRef();
    this.peersRef = []
  }

Then in my componentDidMount(), i initialize the socket.io-client connection to the server. Im using localhost for now:

componentDidMount(){
    this.socket = io('http://localhost:3002', {
      transports: ['websocket']
    });
    var me = this
    this.socket.on('connect', () => me.setState({myId: me.socket.id}));
}

This basically establishes a connection to the server, then sets myId. Then in my render function, i have the following:

render(){
    return (
      <div>
        <h2>My ID: {this.state.myId}</h2>
        <input
            type="text"
            placeholder="Enter ID to call"
            value={this.state.roomId}
            onChange={(e) => this.setRoomId(e.target.value)}
        />
        <button onClick={this.initializeMedia}>Initialize Microphone</button>
        <button onClick={this.joinMultiCall}>Join Call</button>
        
        <audio ref={this.localStream} autoPlay muted />
        {this.state.peers.map((peerObj) => (
          <Audio key={peerObj.peerId} peer={peerObj.peer} />
        ))}
      </div>
    );
 }
setRoomId(value){
  this.setState({roomId: value})
}

initializeMedia = async () => {
  this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  this.localStream.current.srcObject = this.stream;
};

An input for setting the roomId to connect to, a button for requesting a connection to the mic, a button for joining a room, a muted audio thats connected to the stream from my microphone, and a list of peers rendered inside a custom Audio function. Then in the joinMultiCall function, i have the following code:

joinMultiCall = async () => {
    this.socket.emit("join-room", this.state.roomId);

    this.socket.on("user-joined", (userId) => {
      console.log(`User ${userId} joined`); // <------This fires successfully.
      const peer = this.createPeer(userId, this.socket.id, this.stream);
      const peer_obj = { peerId: userId, peer: peer }
      this.peersRef.push(peer_obj);
      var clone = this.state.peers.slice()
      clone.push(peer_obj)
      this.setState({peers: clone})
    })

    this.socket.on("signal", ({ from, data }) => {
      const peerObj = this.peersRef.find((p) => p.peerId === from);
      if (peerObj) {
        peerObj.peer.signal(data);
      }
    });

    this.socket.on("user-left", (userId) => {
      console.log(`User ${userId} left`); //<------- this fires successfully
      this.peersRef = this.peersRef.filter((p) => p.peerId !== userId);
      var clone = this.state.peers.slice()
      clone = clone.filter((p) => p.peerId !== userId);
      this.setState({peers: clone})
    });
 }

  // Create a new peer for an incoming user
 createPeer = (userToSignal, callerId, localStream) => {
    const peer = new SimplePeer({
      initiator: true,
      trickle: false,
      stream: localStream
    });

    // peer.addStream(localStream)

    peer.on('error', err => {
      console.error('Peer error:', err);
    });

    peer.on("signal", (signal) => {
      console.log('signal received,', signal) //<----------This fires too.
      this.socket.emit("signal", { to: userToSignal, data: signal });
    });

    return peer;
 };

The socket emits the ‘join-room’ event successfully because its logged in the console. Also, a signal object is received after a peer object is created. Then when a peer is created, an Audio element is rendered which is supposed to listen for audio streams:

const Audio = ({ peer }) => {
  const ref = useRef();

  useEffect(() => {
      peer.on("stream", (stream) => {
        console.log('stream received, ', stream) //<-------- does not fire
        ref.current.srcObject = stream;
      });
  }, [peer]);

  return <audio ref={ref} autoPlay controls />;
};


class App extends Component { 
...

The ‘stream’ event is not firing here for some reason, and its what is supposed to be streaming all the data to the <audio/> object. My server hosting the socket.io connection:

const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');

const app = express();
app.use(cors());
app.use(express.json({ limit: "10gb" }));
const server = createServer(app);
const io = new Server(server);


io.on("connection", (socket) => {
  console.log("User connected:", socket.id); //<------ logs in the terminal

  // Join a room
  socket.on("join-room", (roomId) => {
    console.log(`${socket.id} joined room: ${roomId}`); //<------ logs in the terminal
    socket.join(roomId);
    socket.to(roomId).emit("user-joined", socket.id);
  });

  // Relay signaling data
  socket.on("signal", ({ to, data }) => {
    io.to(to).emit("signal", { from: socket.id, data });
  });

  // Notify users when someone leaves
  socket.on("disconnect", () => {
    console.log("User disconnected:", socket.id); //<------ logs in the terminal
    io.emit("user-left", socket.id);
  });
});

const IO_PORT = 3002;
server.listen(IO_PORT)

How to return a function value in a Class scope in JS?

I’m trying to write a random ID generator in order to use as an index to a Class that is going to persist users subsciption data into a database. however, I need to make sure this ID is unique to every subscription.

I could make the ID generator work ok, but for some reason I’m not able to return the given ID value to my application.

This is how I’m going through:

First of all I’m declaring the function “generateRamdom” that will create and also make sure I have single IDs by cheking in a .txt file if the ID numbers has been already registered for that given value.

I’m using math.floor and math.random methods to generate random numbers from 1 to 100

There’s a condition checking whether the generated number has been already in my database, if so, a message is sent to the user asking to try again. If the number is not in the database already, I write this number into the database repository and then return it to my application classe.

function generateRandom(){
function generateRandom(){
    let exitGen;
    fs.readFile('test.txt', 'utf-8', (errrs, repoNumbers) => {
        
        const randGen = (Math.floor(Math.random()*100).toString()) + "n";
        if (errrs) throw errrs;
        if(repoNumbers.includes(randGen)){
            const idMsg = '***id already exists. Please try do generate a new ID***';
            exitGen = console.log(idMsg);
            //return exitGen;
            
            }
        
        else{
            fs.appendFile('test.txt', randGen, error => {                            
            if (error) throw error
                exitGen = randGen;

            })
        }

        
                
            

    
    
    return exitGen})

}

console.log(generateRandom());

Here where’s my problem lives:

when I call console.log(generateRadom), node is returning “undefined” when I should get the “exitGen” with the idMsg or randGen variables.

This values of “exitGen” are going to be used in a Class constructor in order move forward with the user subsciption process.

any guess on that?

tried to write a function which returns a variable that respects some conditions

How to push execution js code in middle of it’s execution with it’s memory state

let’s say there is a Node js Server for prime number, it serves to web page one for user input and the other for result

When 1st user demands the nth prime number on the first page, prime number calculation is written in the async-await pattern. Still, the code is executed on the main thread, so while prime number execution is ongoing, that time 2nd user demands the first web page.

Is there a way to push the prime number function with its memory state, serve the page to the second user and then resume the function

Why am I getting CORS policy errors when calling wordnik api from javascript [closed]

I recently switched from an Intel based MacBook Pro to the M4 version. On the old laptop I am able to successfully call the Wordnik API from a browser, Python, CodePen, and Javascript/browser. From the new laptop, I can successfully call the API from a browser, Python, and Codepen but calling from Javascript/browser, I get a CORS error.

Access to fetch at ‘http://api.wordnik.com/v4/word.json/boxer/definitions?&sourceDictionaries=ahd-5&api_key=MYAPIKEY’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Javascript code:

async defineWord() {
  let x = await fetch(http://api.wordnik.com/v4/word.json/boxer/definitions?&sourceDictionaries=ahd-5&api_key=MYAPIKEY);
  this.wordnikData = await x.json()

Again, this works fine on my old laptop as well as Codepen. What security setting am I missing on the new laptop?

CSP error with @crxjs/vite-plugin content scripts

I am using @crxjs/vite-plugin v1.x. Everything works perfectly with it, but when using content_scripts, the browser throws a CSP error despite the correct configuration:

Refused to load the script ‘chrome-extension://…/src/content.ts’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval'”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback

I am experiencing the issue in Chrome 131 and Edge 131 as well.

manifest.config.ts

export default defineManifest(async (env) => ({
  content_scripts: [{
    js: [
      'src/content.ts',
    ],
    matches: [
      'https://stackoverflow.com/*',
    ],
  }],
})

vite.config.ts

import { defineConfig } from 'vite'
import { crx } from '@crxjs/vite-plugin'
import manifest from './manifest.config'

export default defineConfig({
  plugins: [
    crx({ manifest }),
  ],
})

Why can’t Parse fetch existing MongoDB documents by _id despite mapping it to objectId

I have an existing MongoDB database that I want to use with Parse Server. Please note that the data in the database was not created by Parse. Here’s an example of the structure of a document in my theaters collection:

{
  "_id": "59a47286cfa9a3a73e51e72c",
  "theaterId": 1000,
  "location": {
    "address": {
      "street1": "340 W Market",
      "city": "Bloomington",
      "state": "MN",
      "zipcode": "55425"
    },
    "geo": {
      "type": "Point",
      "coordinates": [-93.24565, 44.85466]
    }
  }
}

When I query the collection using ParseQuery, I get results, and Parse seems to automatically map the _id field to an objectId. Here’s my query and the result:

Query:

const query = new Parse.Query("theaters");
const theaters = await query.find();

Result:

[
  {
    "theaterId": 1000,
    "location": {
      "address": {
        "street1": "340 W Market",
        "city": "Bloomington",
        "state": "MN",
        "zipcode": "55425"
      },
      "geo": {
        "type": "Point",
        "coordinates": [-93.24565, 44.85466]
      }
    },
    "objectId": "59a47286cfa9a3a73e51e72c"
  },
  {
    "theaterId": 1003,
    "location": {
      "address": {
        "street1": "45235 Worth Ave.",
        "city": "California",
        "state": "MD",
        "zipcode": "20619"
      },
      "geo": {
        "type": "Point",
        "coordinates": [-76.512016, 38.29697]
      }
    },
    "objectId": "59a47286cfa9a3a73e51e72d"
  }
]

Notice how Parse maps the _id field from MongoDB to objectId in the results.

However, when I try to fetch a single document by its objectId using the following code:

let singleTheaterQuery = new Parse.Query("theaters");
let singleTheater = await singleTheaterQuery.get("59a47286cfa9a3a73e51e72d");

I get the following error:

No object found

What I understand so far:

  • The documents in my database were not created by Parse, so they lack the native objectId field

  • Parse maps _id to objectId when returning results from a find query.

  • Despite this mapping, Parse doesn’t seem to handle get queries properly.

My question: If Parse can map _id to objectId during a find query, why can’t it handle fetching a single object using the get method? Is there a configuration or workaround to enable this behavior, or is this a limitation of Parse when working with existing MongoDB data?

How to Synchronize Audio currentTime Updates and a Custom Slider in a Web Component?

I am building a custom audio player as a Web Component using vanilla JavaScript. The player includes a progress slider and a visual progress bar that should sync with the audio’s current playback time. However, I’m running into issues with keeping the slider and the audio’s currentTime in sync, when users interact with the slider.

Here’s what I’m trying to achieve:

  1. Update the slider position and progress bar as the audio plays (timeupdate event).
  2. Allow users to seek by dragging or clicking on the slider, which should update the audio’s currentTime.

The issues I’m encountering:

  1. When the thumb has been dragged, the slider width as well as the audio’s currentTime always jumps to 0.

This the relevent part of my code:

HTML structure:

<div class="audio-player">
            <div class="play-btn"><svg>...</svg></div>
            <div class="slider-wrapper">
                <div class="audio-progress">
                    <div class="current"></div>
                </div>
                <div class="slider-range"></div>
                <div class="slider-thumb"></div>
            </div>
        </div>

JS:

constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.playerType = "default";

        // Set the default player type
        this.setPlayerType(this.getAttribute('player-type') || "default");

        // Initialize element references
        this.playBtn = this.shadowRoot.querySelector(".play-btn");
        this.sliderWrapper = this.shadowRoot.querySelector(".slider-wrapper");
        this.slider = this.shadowRoot.querySelector(".slider-range");
        this.sliderThumb = this.shadowRoot.querySelector(".slider-thumb");
        this.progress = this.shadowRoot.querySelector(".audio-progress .current");
        this.isLoaded = false;
        this.playing = false;
        this.currentTime = 0;
        this.duration = 0;
        this.isDragging = false;

        this.audio = new Audio();  
        this.audio.crossOrigin = "anonymous"; // For cross-origin support

        // Call the async setup method
        this.initializePlayer();
    }
async initializePlayer() {
        // Set up the audio source
        await this.setAudioSource(this.getAttribute('src'));

        // Add event listeners
        this.playBtn.addEventListener("click", () => this.togglePlay());
        // Log when the input event fires (when slider is moved)
        this.slider.addEventListener("input", (e) => {
            console.log("Slider input event fired");
            this.handleSliderInput(e);
        });

        this.slider.addEventListener("click", (e) => {
            console.log("Slider mouse click event fired");
            this.handleSliderClick(e);
        });


        this.audio.addEventListener("timeupdate", () => { this.updateSliderPosition(); });
        this.audio.addEventListener("play", () => this.handlePlay());
        this.audio.addEventListener("pause", () => this.handlePause());
    }

 // Handle when audio starts playing
    handlePlay() {
        const playIcon = "play-svg";  
        const playIconElement = this.shadowRoot.querySelector(".play-btn svg");
        ...
        playIconElement.setAttribute("data-icon", playIcon); // Set to play icon
    }

    // Handle when audio is paused
    handlePause() {
        const pauseIcon = "pause-svg"; 
        const playIconElement = this.shadowRoot.querySelector(".play-btn svg");
       ...
        playIconElement.setAttribute("data-icon", pauseIcon); // Set to pause icon
    }



updateSliderPosition() {
        if (!this.isDragging) {  // Only update if not dragging
            const currentTime = this.audio.currentTime;
            const duration = this.audio.duration;

            if (duration > 0) {
                const percentage = (currentTime / duration) * 100;
                this.sliderThumb.style.left = `${percentage}%`;
                this.progress.style.width = `${percentage}%`;
                this.slider.value = currentTime;  // Keep slider value synced with audio
            }
        }
    }


handleSliderInput(e) {
        const percentage = (e.target.value / e.target.max) * 100;
        this.sliderThumb.style.left = `${percentage}%`;
        this.progress.style.width = `${percentage}%`;

        // Update the currentTime if not dragging
        if (!this.isDragging) {
            this.audio.currentTime = e.target.value;
        }
    }

    handleSliderClick(e) {
        // Ensure slider moves to the clicked position and updates the audio
        currentTime correctly
        this.isDragging = false;  
        this.updateSliderFromEvent(e);  
    }
    
    // Update slider position and audio currentTime based on the mouse event
    updateSliderFromEvent(e) {
        if (isNaN(this.audio.duration) || this.audio.duration === 0) {
            console.warn("Audio duration is not available yet.");
            return;
        }
        const rect = this.slider.getBoundingClientRect();  
        const offsetX = e.clientX - rect.left;  
        const sliderWidth = rect.width;
        let newTime = (offsetX / sliderWidth) * this.audio.duration;
        console.log("Slider click event: ", { offsetX, sliderWidth, newTime });
        newTime = Math.max(0, Math.min(this.audio.duration, newTime));
        const percentage = (newTime / this.audio.duration) * 100;
        this.sliderThumb.style.left = `${percentage}%`;
        this.progress.style.width = `${percentage}%`;
        this.audio.currentTime = newTime;
  
        // Debugging log to ensure correct audio currentTime is set
        console.log("Audio currentTime set to:", this.audio.currentTime);
    }

Ghost.io Blog “style” variable

I’m working on a Ghost Theme and with the given Ghost Theme I’m working on there’s a code that checks for equality of style to ‘one’ or ‘two’:{{#match style "one"}}
and {{#match style "two"}}

When I check for {{style}} in my case it equals “two”.

My question is where can I set the value for style within Ghost.io so I may set it to ‘one’ and see how the website looks with style set to ‘one’?

Error in implementation of ‘switch’ with regular expressions

The following snippet can be used as a bookmarklet to toggle between multiple websites or pages without typing or even remembering them. Here is the first version, it works fine:

let url;
switch (location.host) {
    case 'github.com':
        url = location.href;
        url = url.replace('github.com', 'stackoverflow.com');
        window.open(url, '_self');
        break;
    case 'stackoverflow.com':
    case 'superuser.com':
    case 'unix.stackexchange.com':
        url = location.href;
        url = url.replace('/.+/', 'www.reddit.com');
        window.open(url, '_self');
        break;
    case 'www.reddit.com':
        url = location.href;
        url = url.replace('www.reddit.com', 'github.com');
        window.open(url, '_self');
        break;
}

Then I tried to further improve it so that it will work not only for unix.stackexchange, but also for english.stackexchange.com, philosophy.stackexchange.com, bicycles.stackexchange.com, and so on.

For this, as suggested by T. J. Crowder in his 2010 answer: https://stackoverflow.com/a/2896642, I added regular expressions. But when I try it in the JavaScript console, it throws an error: SyntaxError: Unexpected token '.'. Expected a ')' or a ',' after a parameter declaration. Why is that, what exactly is wrong here?

function toggle(location.host) {
    let url;
    switch (true) {
        case 'github.com':
            url = location.href;
            url = url.replace('github.com', 'stackoverflow.com');
            window.open(url, '_self');
            break;
        case 'stackoverflow.com':
        case 'superuser.com':
        case /.+.stackexchange.com/.toggle(str):
            url = location.href;
            url = url.replace('/.+/', 'www.reddit.com');
            window.open(url, '_self');
            break;
        case 'www.reddit.com':
            url = location.href;
            url = url.replace('www.reddit.com', 'github.com');
            window.open(url, '_self');
            break;
    }
}

I want to reauthenticate the feathers client user when I refresh?

import { Injectable } from '@angular/core';
import { Application, feathers } from '@feathersjs/feathers';
import socketioClient from '@feathersjs/socketio-client';
import * as io from 'socket.io-client';
import { Router } from '@angular/router';
import * as CryptoJS from 'crypto-js';
import { environment } from 'src/environments/environment.prod';

@Injectable({
  providedIn: 'root',
})
export class FeathersService {
  app!: Application;
  socket;
  constructor(private router: Router) {
    this.socket = io('http://localhost:3030');
    this.app = feathers()
      .configure(socketioClient(this.socket))
      .configure(feathers);

    this.socket.on('connect', () => console.log('Server connected'));

    this.socket.on('connect_error', (err: any) => {});

     this.reauthenticate();
  }
  

  on(event: string, serviceName: string, callback: (data: any) => void) {
    this.app.service(serviceName).on(event, callback);
  }

  async reauthenticate() {
    try {
      const accessToken = await this.decryptToken();

      if (!accessToken) {
        console.log('No token found.');
        sessionStorage.removeItem('token');
        localStorage.removeItem('token');
        return;
      }
      await this.app.service('authentication').create({
        strategy: 'jwt',
        accessToken: accessToken,
      });
    } catch (error) {
      console.log(error);
    }
  }

  decryptToken(): string {
    return CryptoJS.AES.decrypt(
      localStorage.getItem('token') || sessionStorage.getItem('token') || '',
      environment.secretKey
    ).toString(CryptoJS.enc.Utf8);
  }
}

 async logIn(loginCredentials: any): Promise<any> {
    try {
      // const login = await this.feathers.app.authenticate({
      //   strategy: 'local',
      //   ...loginCredentials,
      // });
      const login = await this.feathers.app
        .service('authentication')
        .create({ strategy: 'local', ...loginCredentials });
      console.log(login);

      if (login['accessToken']) {
        if (loginCredentials.keepmeLogin) {
          localStorage.setItem(
            'token',
            CryptoJS.AES.encrypt(
              login['accessToken'],
              environment.secretKey
            ).toString()
          );
        } else {
          sessionStorage.setItem(
            'token',
            CryptoJS.AES.encrypt(
              login['accessToken'],
              environment.secretKey
            ).toString()
          );
        }
      }

I dont want to use feathers/authentication because i will store the token in local or session storage. So i want to manually handle the token on initiall login it fetch the data from the feathers server but when i refresh it throws error like not authentication. so i try to reauthticate the user but still it was fail.