Unable to re-access pop-up window by its window name after navigating out of the page in JavaScript

Hello fellow developers,

I am facing an issue with accessing a pop-up window by its window name after navigating out of the page.

Here are the steps to reproduce the issue:

  • Access a html page on your browser.
  • From there, open a new named popup window:

window.open("/", "testPopup", "width=320,height=240,resizable=yes,scrollbars=yes")

  • Move out from the page to the completely different domain. For example, go to google.com.
  • Hit the back button to the previous page and attempt to access the popup with the following JavaScript code: window.open("", "testPopup")

The browser will open a new blank page instead of returning the Window object of the existing popup.

I have noticed that this technique is still usable up to Chrome 83, but we cannot use it on Chrome 84 onward. (see Access a window by window name)

My question to the community is whether there is any way to access the already opened pop-up window after navigating out from the page. If there is no solution, I would appreciate any suggestions for an alternative workaround.

Thank you in advance for your help.

Non-suffix wildcard in CSP

I’m building an app that allows users to execute code in a sandboxed iframe (think jsbin/etc), but this project has the particular constraint that user code should ideally be immutable.

I could:

  • specify a CSP that doesn’t allow them to import any scripts, but that would be very sub-optimal
  • generate a nonce for imported scripts when they submit code and then add that, but that has some significant downsides given the particular constraints of this project (please trust me here)
  • serve code only from the site’s own domain, but again this has significant down-sides given the constraints of the project

The ideal approach for my particular case would be to restrict users to importing from a set of known-immutable CDN sources like jsdelivr. The problem is that these sources are only immutable if they have the version in the URL.

So, for example:

(it’s possible for a package to be taken down from NPM, but IIUC this only happens in rare circumstances, like if there is copyright violation)

I’m wondering whether there’s any sort of browser mechanism (my first thought was CSP, hence title) that could allow me to enforce that imported scripts are:

  1. from specific domains, and
  2. have the full version in their URL

IIUC, CSP only allows specifying prefixes by including the trailing slash like https://cdn.jsdelivr.net/npm/. It doesn’t allow me to do something like https://cdn.jsdelivr.net/npm/marked@*.*.*/, or even better https://cdn.jsdelivr.net/npm/marked@[0-9]+.[0-9]+.[0-9]+/.

I’m not really expecting that there’s a solution here, but figured I’d ask in case at least one spec author happens to read this and maybe considers a more granular wild-carding system for a future version of the spec. But maybe there is some sort of creative solution here that I haven’t thought of.

Retreive an image and convert it to File with new File()

Is is possible in js to read or get an image in the same folder than the code that execute it and convert it to File?

I specifically need the image to be of this type.

Tried using fetch, could not work since the file will not be exposed to the web.

Also tried using readfilesync, could not figure out how to get the needed data to convert the image to File.

Change the background of selected posts

I use wordpress.

To beautify my site, I want to be able to change the background and color of that part by selecting a part of the writing.

enter image description here

I saw this in some sites but I don’t know how to do it.

p {
        margin: 60px;
        line-height: 36px;
        font-size: 25px;
        text-align: justify;
    }
 <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. At, est, tempore accusantium deserunt omnis non magnam,
        possimus ipsum incidunt corrupti quia? Libero rerum aspernatur consequuntur dolorem quisquam numquam debitis,
        inventore eaque minima corporis explicabo aliquid sit accusamus. Iste beatae aliquam itaque perferendis tempora
        ea sed mollitia quasi totam architecto nisi quia dolorum in laudantium quae eaque quidem consectetur dolor
        eligendi aperiam est, eveniet et similique. Veniam aperiam saepe maiores laboriosam quod necessitatibus aut ea
        ad facere repudiandae, sapiente sequi. Adipisci quia voluptas amet, error, dicta dolore aliquid accusantium
        similique harum ex, at quis consequatur fugit? Maiores modi dolore, magni est laboriosam suscipit obcaecati sint
        esse! Consequuntur, tempora sapiente! Possimus veniam laboriosam distinctio ipsam neque reiciendis minima
        nostrum et atque libero? Adipisci accusamus magni expedita saepe quis, vero quia accusantium. Quod iste dicta
        tempora delectus voluptatum! Distinctio, quaerat fugiat delectus quas commodi facere cupiditate quisquam nobis
        laudantium officia aperiam expedita praesentium laborum voluptatem non, harum ex vel odio molestias quae tempora
        tenetur. Sed soluta illo vero, impedit natus quo rerum dicta beatae iure amet consequuntur nihil laudantium!
        Harum laborum pariatur repudiandae dolore nobis adipisci iure natus veniam commodi voluptatum. Quos reiciendis
        impedit unde eligendi consequuntur, deleniti debitis repudiandae nostrum natus. Quas.
    </p>

Why is my frontend not receiving socket.io events

I have a fun little project going on with mineflayer to make a webgui to control a minecraft console client. I cant seem to catch socket.io events on the frontend js.

app.js

const express = require("express");
const path = require("path");
const { botJump,
    botForward,
    botBackward,
    botLeft,
    botRight,
    botChat,
    botDerpMode,
    botMove,
    botConnect } = require("./botFunctions");
const botFunctions = require("./botFunctions");
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);


io.on('connection', (socket) => {
    console.log(`New connection established on namespace: ${socket.nsp.name}`);
    socket.on('chat message', (msg) => {
        console.log('message: ' + msg);
    });
});

botfunctions.js

const fs = require("fs");
const util = require("util");
const mineflayer = require("mineflayer");
const pathfinder = require("mineflayer-pathfinder").pathfinder;
const { GoalNear } = require("mineflayer-pathfinder").goals;
const { io } = require('socket.io-client');
const socket = io('http://localhost:3000');


let bot;


socket.on('connect', () => {
    console.log('Connected to server');
});

bot.on('messagestr', (msg) => {
   //console.log(msg);
   socket.emit('chat message', msg );
});

Frontend JS

<script src="/socket.io/socket.io.js"></script>
<script>
    const socket = io();
    console.log(socket);
    socket.on('chat message', function(msg) {
        console.log(msg);
    });
    socket.on("connect", () => {
        console.log(socket.connected); // true
    });
    </script>

So obviously a lot of unnecessary code is left out only stuff involved with socket.io.
I receive the console.log from server.js with message: “blah”. but nothing happens on he front end.

What could be causing the ‘setAttribute’ function of a custom Gutenberg block not to work with the save/publish button?

Consider the following blocks.

block.js

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 2,
    "name": "create-block/demo-block",
    "version": "0.1.0",
    "title": "Demo Block",
    "category": "widgets",
    "icon": "smiley",
    "description": "Example block scaffolded with Create Block tool.",
    "attributes": {
        "arr": {
            "type": "array",
            "default": []
        }
    },
    "supports": {
        "html": false
    },
    "textdomain": "demo-block",
    "editorScript": "file:./index.js"
}

edit.js

import {
    useBlockProps,
    InspectorControls
} from '@wordpress/block-editor';

import {
    Panel,
    PanelBody
} from '@wordpress/components';

import './editor.scss';

import { DemoObject } from './demo';

export default function Edit({ attributes, setAttributes }) {
    return (
        <>
            <InspectorControls>
                <Panel>
                    <PanelBody title='Demo Setting'>
                        <DemoObject
                            arr = { attributes.arr }
                            update = { (newArr) => setAttributes({ arr: newArr }) }
                        />
                    </PanelBody>
                </Panel>
            </InspectorControls>
            <p { ...useBlockProps() }>
                { 'Demo Block – hello from the editor!' }
            </p>
        </>
    );
}

demo.js

import { Component } from '@wordpress/element';
import { Button } from '@wordpress/components';

export class DemoObject extends Component {
    constructor(props) {
        super(props);

        this.state = {
            arr: props.arr,
            updater: props.update
        }

        this.increase = this.increase.bind(this);
        this.decrease = this.decrease.bind(this);
    }

    increase() {
        let newArr = this.state.arr;
        newArr.push("");
        this.setState({ arr: newArr });
        this.state.updater(newArr);
    }

    decrease() {
        if (this.state.arr.length > 0) {
            let newArr = this.state.arr;
            newArr.pop();
            this.setState({ arr: newArr });
            this.state.updater(newArr);
        }
    }

    render() {
        return(
            <div>
                <Button onClick={ this.decrease }>decrease</Button>
                <p>{ this.state.arr.length }</p>
                <Button onClick={ this.increase }>increase</Button>
            </div>
        )
    }
}

This block has two buttons in the editor’s settings sidebar. One should increase the array saved in the backend, while the other should decrease it.

It has a strange behavior, though. Upon saving (while editing the site) or publishing (in a post) and then reloading the page, you’ll notice that the array’s length stays the same. If you click the increase button in the site editor, the save button remains disabled. And when using this block in a post, the publish button (although active) does not save the array.

I have seen similar threads, but none has a solution.

How can I set up a metered subscription on Stripe that bills yearly but charges for overage monthly?

So basically I am trying to set up a subscription on stripe where I have a plan that allows 5000 monthly credits and bills a flat $299 yearly. I want to charge customers who exceed their monthly credit usage by the end of every month.

Suppose a customer uses 100 additional credits, I want to bill $0.07 for each additional credit, so by the end of the month, I want to bill them an additional $7.

One idea comes to mind which is to use a combo of a standard pricing model with the $299 charged yearly and a graduated pricing model that charges $0 up to 5000 credits and then charges $0.07 for every credit. But I would need the customer to subscribe to two products.

Is there a better way of doing this?

How to create a collapsible commented out block of code

I’m trying to figure out the specific requirements (if it’s possible) that allows me to collapse/uncollapse a commented out block of code (written in javascript) in Visual Studio Code MacOS.

Please see the image.

image reference

I know {} makes collapsible blocks.

But would like to know how to make commented out collapsible blocks.

sinon Fails to Stub a Module Function

I’m trying to stub a function call in a persistence layer.

This module:

userService.js

const {
User,
sequelize,
require('../../models')

const userIdFor = async (clearID) => {
  return await userIdForParams({ clearID: clearID }, ['id'])
}

const userIdForParams(...)

module.exports = {
  userIdFor,
};

Called by this middleware :

index.js

const { userIdFor, require('./services/modelServices/userService');

class CentralDatabaseManager { constructor() { this.env = process.env.ENV;   }

async copyGroupAssociations(destClearID, sourceClearID) {
  const tabulation = { }

  let destUser = await userIdFor(destClearID);
  if (destUser === null) {
    throw { status: 404, message: `Destination user not found` };
  }
  let sourceUser = await userIdFor(sourceClearID);
  if (sourceUser === null) {
    throw { status: 404, message: `Source user not found` };
  }

  // More to come
}

module.exports = CentralDatabaseManager;

Test:

'use strict';
const sinon = require('sinon');
const userService = require('../services/modelServices/userService');
const CentralDatabaseManager = require('../index');


describe('copyGroupAssociations',() => {   let userIdForStub;

before(() => {
    userIdForStub = sinon.stub(userService, "userIdFor");   });

afterEach(() => {
    userIdForStub.restore();   });

it('should process a happy path operation', async() => {
    userIdForStub.returns(Promise.resolve({"id":427}))
    const tabulation = new CentralDatabaseManager().copyGroupAssociations('3df3ac8a-8985-4efd-bb4a-3f1bdfb0b7a2', '126e5ad3-d8f1-46b9-ac87-543cb3d846d4')   })

})

When called within the test userIdFor() returns the stubbed value, but not within the copyGroupAssociations() context. Is there a way I can stub that?

My case look just like examples found on the sinon site, so I’m not sure where I went wrong.

https://sinonjs.org/how-to/stub-dependency/

Tinymce editor is not updated with separated components in Vue 3

I have using Tinymce editor in my vue 3, and i try to separate the Editor components. This is my Editor.vue components code:

<!-- eslint-disable vue/no-mutating-props -->
<template>
    <div class="mb-6">
        <label class="block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2" :for="id">
            {{ label }} <span class="text-red-600" v-if="isRequired">*</span>
        </label>
        <Editor :id="id" v-model="modelValue" :api-key="apiKey" @input="emit('update:modelValue', modelValue)"
            :init="editorInit" />
        <ValidationMessage :validation="validation" :field="id" />
    </div>
</template>

<script setup>
import Editor from '@tinymce/tinymce-vue'
import ValidationMessage from '@/components/ValidationMessage'

const apiKey = process.env.VUE_APP_TINYMCE_API_KEY

defineProps({
    isRequired: {
        type: Boolean,
        required: true
    },
    label: {
        type: String,
        required: true
    },
    id: {
        type: String,
        required: true
    },
    modelValue: {
        type: String,
        required: true,
        default: ''
    },
    validation: {
        type: Object,
        default: null,
    },
    editorInit: {
        type: Object,
        default: () => ({
            height: 500,
            selector: 'textarea',
            menubar: true,
            plugins: 'link image code lists',
            toolbar: 'undo redo | styleselect | forecolor | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent numlist bullist | link image | code',
        }),
    },
})

const emit = defineEmits(['update:modelValue'])
</script>

And i use that components to my Create.vue parents like this:

//other code
<Editor isRequired label="Deskripsi" id="description" v-model="course.fields.description" :validation="validation" />
//other code
<script setup>

import Editor from '@/components/Form/Editor'

const update = async () => {
    try {
        const updateFields = {
            description: course.fields.description,
        };

        console.log(updateFields);

        await course.updateCourse(router, {
            id: course.fields._id,
            data: updateFields,
        });
    } catch (error) {
        validation.value = error
    }
}
</script>

but why the description field value is not updated? I have other Input text components like this, and its working normally, but not with this tinymce editor

Replace unicode characters in html returned from node js web scraper

I have a web scraper that uses cheerio. My goal is to get a list of all the links on the page, however I have noticed that some links do not show up due to unicode greater than and less than characters replacing the opening and closing tags.

How would I best replace these instances of unicode? I have tried the normalize() method but this does not seem to work.

Here is the code

import fetch from 'node-fetch'
import { load } from 'cheerio'

const response = await fetch('https://www.kapow.com/')
const html = await response.text()
const $ = load(html)

const links = $('a')
  .map((i, link) => link.attribs.href)
  .get()

console.log(links)

Here is a screenshot of the unicode characters I am trying to replace highlighted in blue. Ideally I would be able to replace all the unicode such as u003c and u003e:

enter image description here

React/Ruby on Rails: Uncaught TypeError: Cannot read properties of undefined (reading ‘id’) when passing down mapped prop

I’ve been really pulling my hair out over this bug as I’ve been troubleshooting it for the past few days and haven’t found any reliable answers.

My goal is to be able to route to an individual component, [http://localhost:4000/hris/employees/1] and show that individual ’employee’ card on a routed page.

In my App.js component, I believe I have everything routed properly:

<Route exact path="/hris/employees">
            <Employees 
              employees={employees}
              setEmployees={setEmployees}
              addresses={addresses}
              setAddresses={setAddresses}
              zips={zips}
              setZips={setZips}
              skills={skills}
              setSkills={setSkills}
              onSubmitNewEmployee={onSubmitNewEmployee}
              onSubmitNewSkill={onSubmitNewSkill}
              onSubmitNewAddress={onSubmitNewAddress}
              displayCard={displayCard}
              setDisplayCard={setDisplayCard}
            />
          </Route>

          <Route exact path="/hris/employees/:id">
            <Employee />
          </Route>

Then here is the Employees.js component:

import React from "react"
import Employee from './Employee'
import EmployeeForm from './EmployeeForm'

function Employees({
    employees,
    setEmployees,
    addresses,
    setAddresses,
    zips,
    setZips,
    skills,
    setSkills,
    onShowDetails,
    displayCard,
    setDisplayCard
}) {

    return (
        <div>
            <div className="container">
                <h1>Employees</h1>
                <br/>
                <div className="card-container">
                    <div className="cards">
                        {employees.length > 0 ? 
                            employees.map(employee =>
                                <Employee
                                    key={employee.id}
                                    employee={employee}
                                    test={console.log(employee.id)}
                                />) : null }
                    </div>
                </div>
                <br />
                <div>
                    <EmployeeForm
                        employees={employees}
                        setEmployees={setEmployees}
                        addresses={addresses}
                        setAddresses={setAddresses}
                        zips={zips}
                        setZips={setZips}
                        skills={skills}
                        setSkills={setSkills}
                        onShowDetails={onShowDetails}
                        displayCard={displayCard}
                        setDisplayCard={setDisplayCard}
                    />
                </div>
            </div>
        </div>
    )
}

export default Employees

The important code to look at here is the following:

<div className="card-container">
                    <div className="cards">
                        {employees.length > 0 ? 
                            employees.map(employee =>
                                <Employee
                                    key={employee.id}
                                    employee={employee}
                                    test={console.log(employee.id)}
                                />) : null }
                    </div>
                </div>

With this, the <Employee /> component is then mapped out and the data appears perfectly fine in the <Employees /> component with each card populating within the <div className="cards">...</div> . Please see the following image as an example:

Employees Component, Employee Map Working

When I console.log(employee.id) within the test prop in Employee, I get the following log:

Console Log looking good!

When I go into Postman, the route works fine too!

HOWEVER, once I’m in the <Employee /> component, here are the code and the issues I receive:

import React from "react"
import { Link } from 'react-router-dom'

function Employee({
    employee,
    test
}) {
    
    console.log(employee.id)
    console.log(test)
    const data = employee.skills
    const listSkills = data.map((data) => <li key={data.skill_name}>{data.skill_name}</li>)

    return (
        <div className="card-spacing">
            <div className="card">
                <div className="card-details">
                    <ul className="cards-ul">
                        <li className="card-li">
                            <div>
                            <Link to={`/employees/${employee.id}`}></Link>
                            <div>
                                <h3>{employee.first_name} {employee.middle_name} {employee.last_name} {employee.suffix}</h3>
                                <p><>Role:</> <>{employee.job_title}</></p>
                                <p><>Contact Info:</><br/><>Phone: <><ul>{employee.emp_phone}</ul></></><>Email: </><ul>{employee.emp_email}</ul></p>
                                <p><>Address:</><br/><ul><>{employee.address.line_one}, {employee.address.line_two}</><br/><>{employee.address.zip.city}, {employee.address.zip.state} {employee.address.zip.zip_code}</></ul></p>
                                <p><>Gender: </>{employee.gender}</p>
                                <p><>SSN/Tax ID: </> ***-**-{employee.tax_number.slice(7, 11)}</p>
                                <p>Start Date: {employee.start_date}</p>
                                <p>Compensation: {employee.hourly_or_salary}</p>
                                <p>Hourly-Rate: ${employee.hourly_rate}</p>
                                <p>Annual-Salary: ${employee.annual_salary}</p>
                                <p>PTO Policy: <br/><ul><>{employee.pto_policy}</></ul></p>
                                <div>Skills: <br/><ul>{listSkills}</ul></div>
                                <p>Notes: <br/>{employee.emp_notes}</p>
                                <br/>
                            </div>
                            <div className="card-buttons">
                                <button>Edit</button>
                                <button>Expand/Collapse</button>
                            </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    )
}

export default Employee

This data within the return () works perfectly when in [localhost:4000/hris/employees], but in this current situation, but I keep receiving the following error after console.logging my issue and checking the [localhost:4000/hris/employees/1] route:

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

and

The above error occurred in the <Employee> component:

I’m floored because I’ve done this a ton of times before and have never run into this before. The map should work fine.

I’ve tried doing the following to no avail:
employees.map(employee => (the “standard”)
employees.map(employeeMap =>
employees && employees.map(employee =>
employees && employees.map(employeeMap =>
employees?.map(employee =>
employees?.map(employeeMap =>
employees && employees?map(employee =>
employees && employees?map(employeeMap =>

Could anybody provide some context? Thanks!

Dynamically update lit CSS module based on attribute

I have a component that I want to style/theme based on an attribute. Depending on the attribute value, I want to import a different stylesheet/css module.

Ideally it would be something along the lines of

import module1 from 'css-module1.js'
import module2 from 'css-module2.js'

@customElement('component')
export class Component extends LitElement {
  static styles = attribute ? [module1] : [module2]

  @property({reflect: true})
  attribute = <value>

  <rest of file>
}

Everything I see suggests that dynamic attribute based css only works for

static styles = css`
  :host([attribute]) { <css> }
`

Is it possible to dynamically assign the style based on an attribute? The stylesheet is too large to realistically put multiple attribute based copies within the file itself.

Electron-build not copying over additional html files

I’m using the boilerplate from electron-forge to construct an electron app that I would like to package. The main window is wrapped in an additional “gate” window that I’m using as a license check.

in main.ts, the relevant code:

const gateCreateWindowWithLicense = async (createWindow: any) => {
  const path = require('path');
  

  gateWindow = new BrowserWindow({
    resizable: false,
    frame: false,
    width: 420,
    height: 200,
    webPreferences: {
      preload: path.join(__dirname, '/gate.js'),
      devTools: isDebug,
    },
  });
  gateWindow.loadFile(`${__dirname}/gate.html`);

The structure of the project is:

-project
--node_modules
--src
----render
----main
------gate.css
------gate.html
------gate.js
------main.ts
------preload.ts
------menu.ts

When I package and attempt to run the app, it just loads a blank white screen that is the size of the gate window (but no other controls/features). When I launch the app locally via commandline (found inside /release/build):

(base) user@computer:~/project/release/build$ ./project.AppImage 
(node:2740) electron: Failed to load URL: file:///tmp/.mount_EspritQdcf5k/resources/app/gate.html with error: ERR_FILE_NOT_FOUND

How do I make it so that all of the gate files are moved in with the project? I’ve read about the “files” tag in project.json but I dont know where the “to” directory is after its been packaged.

How can I paste the values ​of an array into another array

I have an array called “valores”. This array is divided into columns and within the columns their corresponding tasks (rows).

I have another array called “valValues” (the main one) that contains several arrays inside. It is also divided by columns first and within each column, its corresponding rows. The first element is the day of the month. The second element is the “Progress Bar”. From the third element to the fifteenth element are empty rows where the values ​​of the “values” array must be pasted.

How can I paste the values ​​from the “valores” array into the “valValues” array from the 3 column array element into the “valValues” array?

enter image description here

This is the code:

function importarTareasGlobal23(){

  ... // here is more code

  var filasDestino = sheetCalendario.getRangeList(['E4:E18', 'H4:H18', 'K4:K18', 'N4:N18', 'Q4:Q18', 'T4:T18', 'W4:W18', 'E20:E34', 'H20:H34', 'K20:K34', 'N20:N34', 'Q20:Q34', 'T20:T34', 'W20:W34', 'E36:E50', 'H36:H50', 'K36:K50', 'N36:N50', 'Q36:Q50', 'T36:T50', 'W36:W50', 'E52:E66', 'H52:H66', 'K52:K66', 'N52:N66', 'Q52:Q66', 'T52:T66', 'W52:W66', 'E68:E82', 'H68:H82', 'K68:K82', 'N68:N82', 'Q68:Q82', 'T68:T82', 'W68:W82', 'E84:E98', 'H84:H98', 'K84:K98', 'N84:N98', 'Q84:Q98', 'T84:T98', 'W84:W98']);
  var filasDestinoVal = filasDestino.getRanges();

  var tabladebusquedaVal = sheetTareas.getRange("B5:H" + lastRowTareas).getValues();

  var valValues = [];
  var valores = [];

  filasDestinoVal.forEach(row => {
    var val = row.getValues();
    valValues.push(val);
    
    ... // here is more code

    var resultados = [];

    tabladebusquedaVal.forEach(r => {
      ... // here is more code     
      if ( ... ) {
        resultados.push([icoTarea]);
      }
    });
    valores.push(resultados);
  });

  Logger.log(valores);
  Logger.log(valValues);
}