How to clear before paste in Javascript?

I’m using the code below to paste a string into a DOM element (in this case a DIV element in a React website).

The code works but if the element has already some text, the code will paste my string AFTER the current text and what i want is , the field ends up ONLY with my text. How can i clear the field content before pasting ?

I know it would be better to use .value or .innerText but there are some limitations in the specific site i’m dealing avoiding me to use a simpler approach (it’s a React site), so that’s why i’m using the clipboard method instead, it’s the only one that works.

let el = document.getElementsByClassName('xzsf02u x1a2a7pz x1n2onr6 x14wi4xw x9f619 x1lliihq x5yr21d xh8yej3 notranslate')[0];
const dataTransfer = new DataTransfer();
dataTransfer.setData('text','testing one two three');
const event = new ClipboardEvent('paste', {clipboardData: dataTransfer,bubbles: true});
el.focus();
el.dispatchEvent(event);
el.focus();

The Node.js application using the dotenv package fails to read environment variables from the .env file. As a result, the following error occurs:

C:UsersuserDesktopNexoGame-b>npm run server

> [email protected] server
> nodemon server.js      

[nodemon] 3.1.10
[nodemon] to restart at any time, enter `rs`  
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js`
C:UsersuserDesktopNexoGame-bnode_modulespassport-oauth2libstrategy.js:87
  if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
                                 ^

TypeError: OAuth2Strategy requires a clientID option
    at Strategy.OAuth2Strategy (C:UsersuserDesktopNexoGame-bnode_modulespassport-oauth2libstrategy.js:87:34)
    at new Strategy (C:UsersuserDesktopNexoGame-bnode_modulespassport-google-oauth20libstrategy.js:52:18)
    at file:///C:/Users/user/Desktop/NexoGame-b/config/passport.js:6:3
    at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:578:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:116:5)

Node.js v22.14.0
[nodemon] app crashed - waiting for file changes before starting...` The .env file is not being recognized correctly on Windows.

Details:
The user created a file named .env, but due to Windows File Explorer behavior, it actually saved the file with a hidden extension (e.g., .env.txt or .env.3dsenv).

The dotenv package only looks for a file exactly named .env, without any extension.

Because of this mismatch, dotenv.config() silently fails to load the environment variables.

As a result, process.env.GOOGLE_CLIENT_ID and similar variables remain undefined, causing the OAuth strategy to throw an error due to missing configuration.

Artificial intelligence says these are the reasons. I deleted the .env file and rewrote it again, but it didn’t work, I still get the same error. This website is being sent to github and I cannot open a new one. Whatever I need to do, I need to write everything in this back folder. I don’t have the chance to create a new repo, so I commit every day.

I created a .env file in the root of my Node.js project and added the following environment variables:

GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here

In my server.js, I used:

import dotenv from 'dotenv';
dotenv.config();

console.log('GOOGLE_CLIENT_ID:', process.env.GOOGLE_CLIENT_ID);

I expected the GOOGLE_CLIENT_ID to print its value from the .env file. However, it always logs undefined, and the app crashes with this error:

TypeError: OAuth2Strategy requires a clientID option

Cloud Run service has SSL certificate error, causing Failed to fetch from Chrome Extension

I have a Google Cloud Run service that I am trying to call from my Chrome Extension, but the request fails. Here is my setup and the issues I’m encountering.

Goal: My Chrome Extension popup makes a fetch POST request to my Cloud Run service.

The Problem:

When called from the extension, the fetch call instantly fails with TypeError: Failed to fetch.
When I test the endpoint directly from my computer’s terminal using curl, I get a specific SSL error: curl: (60) SSL: no alternative certificate subject name matches target host name 'command-processor-[PROJECT_ID]-us-central1.run.app'

What I Have Verified:

  • My Cloud Run service deploys successfully without any “container failed to start” errors.
  • My extension’s manifest.json has the correct host_permissions for the https://*.run.app/ domain.
  • My extension’s manifest.json has the “downloads” permission.
    The URL in my extension’s fetch call exactly matches the URL of the deployed service.

This seems to be an SSL certificate provisioning or mapping issue on the Cloud Run service itself. Why would a default service on a .run.app URL be serving a mismatched certificate, and what are the steps within Google Cloud to debug or force-refresh the SSL certificate for the service?

Backend Code (index.js):

// index.js (Corrected for Google Cloud Functions Framework)

const functions = require('@google-cloud/functions-framework');
const { google } = require('googleapis');
// This is the correct way to use cors with this framework
const cors = require('cors')({ origin: true });

// IMPORTANT: Replace this with your actual API key if needed.
const API_KEY = '**************';


// This is the single entry point for your Cloud Function
functions.http("commandProcessor", (req, res) => {
  
  // The cors function handles the OPTIONS pre-flight request and then calls the callback.
  cors(req, res, async () => {
    try {
      // --- Route 1: Handle the new /summarize-chat endpoint ---
      if (req.path === '/summarize-chat') {
        if (req.method !== 'POST') {
          return res.status(405).send('Method Not Allowed');
        }
        console.log("Handling request for /summarize-chat");
        const transcript = req.body.transcript;
        if (!transcript) {
          return res.status(400).json({ error: 'No transcript provided.' });
        }
        const summary = `### Chat Session Summaryn**Date:** ${new Date().toISOString()}nn**Raw Transcript:**n---n${transcript}n---`;
        return res.status(200).json({ summary: summary });
      }

      // --- Route 2: Handle all other requests as Drive commands (your original logic) ---
      console.log("Handling request for Drive command processor.");

      if (req.get('x-api-key') !== API_KEY) {
        console.error("Unauthorized request: API key missing or incorrect.");
        return res.status(401).send('Unauthorized');
      }

      if (req.method !== 'POST') {
        return res.status(405).send('Method Not Allowed. Only POST is supported.');
      }
      
      const commandObject = req.body;
      // ... (The rest of your original Drive command logic starts here and is unchanged)
      if (!commandObject || !commandObject.command || !commandObject.parameters) {
        console.error("Invalid command format received. Expected {command: 'CMD', parameters: [...]}.");
        return res.status(400).send("Invalid command format.");
      }
  
      const authHeader = req.get('Authorization');
      let userAuthToken = null;
      if (authHeader && authHeader.startsWith('Bearer ')) {
        userAuthToken = authHeader.substring(7);
      } else {
        console.warn("No Bearer token provided by client. This command might fail if it requires user-specific Drive access.");
      }
  
      console.log(`Cloud Run: Received raw command object: ${JSON.stringify(commandObject)}`);
      console.log(`Cloud Run: Command extracted for switch: ${commandObject.command.toUpperCase()}`);
  
      let result;
      switch (commandObject.command.toUpperCase()) {
        case 'DRIVE_CREATE_PROJECT':
          result = await createProjectInDrive(commandObject.parameters[0], userAuthToken);
          break;
        // Add your other cases for DRIVE_CREATE_FILE, DRIVE_MOVE_FILE, etc. back in here
        default:
          result = { success: false, message: `Unknown Drive command: ${commandObject.command}.` };
          break;
      }
  
      if (result.success) {
        res.status(200).json({ status: 'success', message: result.message, data: result.data });
      } else {
        res.status(500).json({ status: 'error', message: result.message });
      }

    } catch (error) {
      console.error('Unhandled error in function:', error);
      res.status(500).json({ status: 'error', message: `Internal server error: ${error.message}` });
    }
  });
});


// --- All existing Google Drive helper functions remain here, unchanged ---
async function getDriveClient(token) {
    // ... (your existing function)
}
async function createProjectInDrive(projectName, token) {
    // ... (your existing function)
}
// ... etc for all other helper functions.

Manifest File (manifest.json):

{
  "manifest_version": 3,
  "name": "My Life AI Drive Extension",
  "version": "1.2",
  "description": "A private extension to allow My Life AI (Bob) to assist with Google Drive file management.",
  "permissions": [
    "identity",
    "storage",
    "notifications",
    "downloads"
],
  "host_permissions": [
    "https://*.google.com/",
    "https://*.googleapis.com/",
    "https://https://command-processor-[PROJECT_ID]-us-central1.run.app/*"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html",
    "default_title": "My Life AI Drive Commands"
  },
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  },
  "oauth2": {
    "client_id": "[YOUR_OAUTH_CLIENT_ID].apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/drive"
    ]
  }
}

Attempting to make a lightbox, Images not loading

Expected to happen: Clicking on image will make it appear inside lightbox which covers screen

What actually happened: Lightbox appears, image doesnt load

I’m very new to all kinds of programming so this is very confusing
I was told I need to put the images in an array but I don’t know how to actually apply that to my code. example

heres the website where this is broken: https://teddydemonenjoyer.neocities.org/zchar_syalis
Minimal Reprodoucible Example on codepen: https://codepen.io/Teddy-Demon-Enjoyer/pen/PwqBGOQ

HTML:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minimal Reproducible Example</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script defer src="/js/script.js"></script>
</head>
<body>
<article>
<div class="character-table">
 <table>
  <th colspan="2">
  <div class="appearance-select">
  <tr>
  <td colspan="2">
    <img id="syaImg" src="https://cdn.pixabay.com/photo/2016/11/30/20/58/programming-1873854_960_720.png" width="375px" height="505">
  </td>
  </tr>
  </div>
  </div>
  </div>
</table>
</div>
<div class="page-body">

<div class="character-page">
 <p><img src="https://media.istockphoto.com/id/1047259374/photo/programming-source-code-abstract-background.webp?s=2048x2048&w=is&k=20&c=JjAc-lnJXIFeH3Jb25ICSEseUHeGfToOleoJpiHjLGA="></p>
</div>
</div>
</body>
</html>

css:

#lightbox {
position: fixed;
z-index: 1000;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: none;
}
#lightbox.active {
display: flex;
justify-content: center;
align-items: center;
}
#lightbox img {
max-width: 90%;
max-height: 80%;
padding: 4px;
background-color: linear-gradient(180deg, #251047 15%, rgba(95, 47, 125, 1) 75%, rgba(139, 58, 171, 1) 100%);
border: 1px dotted white;
}

js:

const lightbox = document.createElement('div')
lightbox.id = 'lightbox'
document.body.appendChild(lightbox)

const images = document.querySelectorAll('img')
images.forEach(Image => {
    Image.addEventListener('click', e => {
        lightbox.classList.add('active')
        const img = document.createElement('img')
        img.src = images.src
        while (lightbox.firstChild) {
            lightbox.removeChild(lightbox.firstChild)
        }
        lightbox.appendChild(img)
    })
})

lightbox.addEventListener('click', e => {
    if (e.target !== e.currentTarget) return
    lightbox.classList.remove('active')
})

I don’t know what to try without breaking everything, I would just like the images to load.

Recursive function causing incorrect sequence order

Why is MoveToFirstError Called Before LinkedFormWithErrorID is Set in Form Validation Logic?
I’m working on a JavaScript form validation system that handles both a main form and linked forms (e.g., forms in modals). The issue is that MoveToFirstError is called before LinkedFormWithErrorID is set, causing the modal containing the linked form with errors to remain hidden. Additionally, the console logs show an unexpected sequence, indicating a timing issue in my validation logic.

Code Description

My validateForm function validates a main form and any linked forms specified via a LinkedForms attribute. If errors are found in a linked form, I set a global LinkedFormWithErrorID to the ID of the errored form and return early. After validation, if FormErrors > 0, I call MoveToFirstError to focus on the first error, which should also show the modal if the error is in a linked form.

However, the console logs show:

1-false

2-Setting LinkedFormWithErrorID to LayoutSelectModal

3-Form has 3 errors, not submitting.

This suggests MoveToFirstError runs before LinkedFormWithErrorID is set, so the modal doesn’t appear. The main form has no errors; all errors are in the linked form (LayoutSelectModal).

Problem Description

In my case:

The main form is error-free (FormErrors remains 0 after its validation).

The first linked form, LayoutSelectModal, has three errors, causing FormErrors to become 3.

When errors are found in a linked form, I set the global LinkedFormWithErrorID to the ID of the errored form (e.g., “LayoutSelectModal”) and return early to stop further validation.

After validation, if FormErrors > 0, I call MoveToFirstError to focus on the first error, which should also unhide the modal if the error is in a linked form.

Expected Behavior

1-Complete all validation (main and linked forms) first (return early as soon as an error is encountered with any form skipping further unnecessary validation ).

2-Set LinkedFormWithErrorID if a linked form has errors.

3-Call MoveToFirstError once, after validation, to focus on the first error and show the modal if needed.

4-Console logs should show Setting LinkedFormWithErrorID to LayoutSelectModal before false from MoveToFirstError.

Relevant Code
validateForm Function
This validates the main form and linked forms, setting FormErrors and LinkedFormWithErrorID.

let FormErrors = 0; // Global error counter
let LinkedFormWithErrorID = false; // Tracks ID of errored linked form

function validateForm(Form) {
    FormErrors = 0;
    let InputGroups = Form.getElementsByClassName("InputGroup");
    // ... (input group validation logic omitted for brevity) ...

    // Linked Forms Validation
    LinkedFormWithErrorID = false; // Reset
    if (Form.hasAttribute("LinkedForms")) {
        const linkedFormIds = Form.getAttribute("LinkedForms").split(",").map((id) => id.trim());
        for (const linkedFormId of linkedFormIds) {
            const linkedForm = document.getElementById(linkedFormId);
            if (linkedForm) {
                const isValid = validateForm(linkedForm); // Recursive call
                if (!isValid) {
                    LinkedFormWithErrorID = linkedFormId;
                    console.log("Setting LinkedFormWithErrorID to " + LinkedFormWithErrorID);
                    return false; // Early return on error
                }
            } else {
                console.warn(`Linked form with ID "${linkedFormId}" not found.`);
            }
        }
    }

    // Check for errors
    if (FormErrors > 0) {
        MoveToFirstError(Form); // Focus on first error
        return false;
    } else {
        return true;
    }
}

MoveToFirstError Function

This focuses on the first error in the main form or linked form and should show the modal if needed.
function MoveToFirstError(form) {
    console.log(LinkedFormWithErrorID); // Logs 'false' first
    const firstError = form.getElementsByClassName('Error')[0];
    if (firstError) {
        firstError.focus();
        firstError.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        if (form.hasAttribute('MultiPage')) {
            ShowFirstErrorFormStep(form, firstError);
        }
        return false;
    }

    if (LinkedFormWithErrorID) {
        const linkedForm = document.getElementById(LinkedFormWithErrorID);
        if (linkedForm) {
            if (linkedForm.parentNode.parentNode.classList.contains('modal')) {
                linkedForm.parentNode.parentNode.classList.remove('hidden'); // Show modal
            }
            linkedForm.classList.remove('hidden');
            const firstError = linkedForm.getElementsByClassName('Error')[0];
            if (firstError) {
                firstError.focus();
                firstError.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            return false;
        }
    }

    return true;
}

SubmitForm Function

This triggers validation and submission.
async function SubmitForm(Form, ReqMethod, ReqTarget, formData) {
    if (Form) {
        validateForm(Form);
        if (FormErrors > 0) {
            console.warn("Form has " + FormErrors + " errors, not submitting.");
            return {
                success: false,
                message: "Form has " + FormErrors + " errors, not submitting.",
            };
        }
        // ... (data collection and submission logic omitted) ...
    }
    // ... (fetch logic omitted) ...
}

Questions

Why is MoveToFirstError called before LinkedFormWithErrorID is set?
How can I ensure all validation completes before focusing on the first error?
What changes are needed to make the modal appear when errors are in a linked form?

Any help or insights would be greatly appreciated!

Vue 3 + Jest: Function doesn’t trigger expected state change in test

I’m writing unit tests for a Vue 3 component using the Composition API, Vue Test Utils, and Jest. The component has a method that triggers an API call and updates a step variable based on the result. However, in my test case, even after mocking the store and calling the function, the expected step change doesn’t happen.

MyComponent.vue

const connectService = async () => {
  loading.value = true;

  const payload = {
    type: 'messaging',
    credentials: {
      username: user.value,
      password: pass.value,
      ...(phone.value && { phoneNumber: phone.value })
    }
  };

  try {
    await store.connect(payload);
    if (store.connectionStatus === 'connected') {
      if (requiresVerification.value) {
        step.value = 'VerifyAccount';
      } else {
        step.value = 'SuccessScreen';
      }
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

test.spec.ts

wrapper.vm.phone = '+1234567890';

// Mock store response before calling function
store.$patch({
  connectionStatus: 'connected'
});

wrapper.vm.requiresVerification = false;

// Call the function
await wrapper.vm.connectService();

// Let Vue resolve everything
await wrapper.vm.$nextTick();

// Expect the `step` to update
expect(wrapper.vm.step).toBe('SuccessScreen');

The test fails. The step is still the initial value and doesn’t update to ‘SuccessScreen’. What I noticed is that wrapper.vm.phone is updating properly, but connectionStatus is not.

My environment details are-

"vue": "3.5.13",
"@vue/test-utils": "2.4.6",
"vite": "6.2.5",

Can anyone please help me understand what I’m doing wrong?

JavaScript fetch body empty when using CloudFlare

I’m not even sure where to start with this…

Basically:

  • My POST requests work fine when connecting to the IP directly
  • When I connect via CloudFlare the POST request gets received by the Server, but there’s no content?

Here’s the raw HTTP request:

POST /test HTTP/1.1
cf-ray: ...
x-forwarded-for: ...
Host: ...
cookie: ...
accept-encoding: gzip, br
cdn-loop: cloudflare; loops=1
X-Forwarded-Proto: https
priority: u=1, i
accept-language: en-US,en;q=0.9,de;q=0.8
CF-Visitor: {"scheme":"https"}
referer: ...
sec-fetch-dest: empty
CF-Connecting-IP: ...
CF-IPCountry: DE
sec-fetch-mode: cors
Connection: Keep-Alive
Content-Length: 17
sec-fetch-site: same-origin
sec-ch-ua-full-version-list: "Google Chrome";v="137.0.7151.104", "Chromium";v="137.0.7151.104", "Not/A)Brand";v="24.0.0.
0"
sec-ch-ua-platform: "Windows"
sec-ch-ua: "Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"
sec-ch-ua-bitness: "64"
sec-ch-ua-model: ""
sec-ch-ua-mobile: ?0
sec-ch-ua-arch: "x86"
sec-ch-ua-full-version: "137.0.7151.104"
accept: application/json
content-type: application/json
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537
.36
sec-ch-ua-platform-version: "10.0.0"
origin: ...


The Content-Length header is set, but there is no content?
I’m so confused with this…

Here is the code I used to make this test POST request:

fetch("/test", 
    { 
        method:"POST", 
        headers: {
            "Accept":"application/json", 
            "Content-Type":"application/json"
        }, 
        body:JSON.stringify({hello:"world"})
    }
)

Any help is appreciated!

How can I cache video content with tag in React?

I have this piece of code:

<video
  ref={videoEl}
  width={videoWidth}
  height={videoHeight}
  controls={true}
  preload="auto"
  onPlay={onPlayClick}>
  <source src={videoUrl} type="video/webm" />
</video>

videoUrl comes to the component via props. I’m trying to do HTTP caching of the video. In the header of the response from the server via videoUrl I have the header Cache-Control: public,max-age=86400. While the video is cached and subsequent requests no longer go to this URL

However at the same time in the player I do not have access to the entire video. For example, the video starts at 0:00 and the entire video is loaded as if it was watched to the end. Only then I would see 0:05/0:07. In Firefox it seems like caching works every other time and the entire video is loaded. Responses from the server come to me as 206 Partial Content.

Is it possible to cache video in the player via the <video> tag or is this some kind of default limitation? Maybe it has something to do with the the video/webm type, I’m open to any discussions and questions, I really want to figure out what’s going on.

I tried caching via Service Workers, but in my opinion it’s not a very good solution, and I want to understand if it can be done via HTTP caching. Maybe I somehow misunderstood the principle of HTTP caching and I need to change something in the server?

How to get the attributes of the currently active widget in Elementor editor via JavaScript?

I’m building a custom Elementor extension and need to access the attributes (settings/controls) of the currently selected widget in the Elementor editor using JavaScript.

So far, I’ve tried inspecting panelView and various parts of the elementor JS namespace. However, I can’t seem to get a reliable reference to the currently active widget instance (the widgetModel) in order to call getSetting() or inspect its data.

There can be multiple widgets of the same type on the page, so I need the specific instance that is currently being edited.

I’ve tried using jQuery to find elements with data-setting or tracing the view stack, but nothing solid so far.

How can I get the currently active widget’s model (widgetModel) in Elementor editor so I can inspect or manipulate its settings?

How to implement accessible, semantic HTML for custom-styled form while maintaining compatibility across screen readers, without relying on JavaScript [closed]

I’m currently working on a sleek, visually customized form design, but I’ve hit a wall. The styling is breaking semantic structure, and screen readers aren’t handling it well. Since I want to keep things HTML/CSS-only (no JavaScript workarounds), I’m struggling to preserve accessibility features—like clear label associations, logical focus order, and proper ARIA roles—without sacrificing the design

How to use the same configuration file in both content scripts and background module in Manifest V3?

I’m developing a Chrome extension using Manifest V3.
My background script is a module (“type”: “module”), so it uses import { CONFIG } from ‘./config.js’;.
My content scripts, however, can’t use ES6 imports/exports and need to access the config via window.CONFIG.

Is there a way to use a single configuration file for both contexts without duplicating code?
If not, what’s the best practice for sharing config between background (module) and content scripts?

Thanks!

I tried creating a single config.js file that both attaches the config object to window (for content scripts) and exports it (for the background module).
However, using export in a script loaded as a content script causes a syntax error, and omitting export means I can’t import it in the background module.
I was expecting to be able to share the same config file between both contexts without errors or code duplication.

manifest.json

“content_scripts”: [ { “js”: [ “config.js”, “content.js” ], “run_at”: “document_end”, “matches”: [ … ], “exclude_matches”: [ … ] } ], … “background”: { “service_worker”: “background.js”, “type”: “module” },

config.js

const CONFIG = { // … }

if (typeof window !== ‘undefined’) { console.log(“Entering config.mjs in window”); window.CONFIG = CONFIG; }

export { CONFIG };

content.js

const CONFIG = window.CONFIG;

background.js

import { CONFIG } from ‘./config.js’;

Any advice or best practices would be appreciated!

function losses it’s this context when passed in tanstack/react-query-devtools as the queryFn [duplicate]

I am using "@tanstack/react-query-devtools": "^5.69.0" in my react project. And i am passing one of the arguments conditionally by binding it to the this context object of the function. In simple words if i need to send the argument i bind it with the help of .bind() function.

Issue:
The issue is for some reason the function i provide cannot access the value even though in the chrome devtools while debugging i can see the object being attached as [[BoundThis]] to my function.

File1.js

export const bindContext = (fn, id) => {
    return id ? fn.bind({ id }) : fn;
};

File2.js

export const useFetchBlogs = ( id) => useQuery({
        queryKey: ['blogsList', id],
        queryFn: () => bindContext(fetchBlogsFn, id)(),
        enabled: true,
        refetchOnMount: true,
        refetchOnWindowFocus: false,
        staleTime: 10 * 60 * 1000, // 10 minutes
        retry: 1 // retry only once if query fails
    });

File3.js

export const fetchBlogsFn= ()=> {
    console.log('useFetchBlogs called', this); // getting this as undefined in the devtools
    
    const queryConfig = {
        ... this?.id ? { params: { blogId: this.id } } : {}
    }

    return new Promise((resolve, reject) => {
        httpService.load(URLS.PRIORITIES, queryConfig).then(
            res => {
                const transformedData = dropdownOptions(res);

                resolve(transformedData);
            },
            err => reject(err)
        );
    });
};

What’s happening ?
I can see while debugging that the object containing the id is attached as [[BoundThis]] to the returned function but as soon as the function call is invoked and the debugger goes inside the function, the this context object becomes undefined

I think that the way react query is calling the queryFn is manipulating the this context.

I tried using the function expression syntax in place of the arrow funcitons as well but it did not work… neither did the strategy to first bind the id and then pass the bound function as argument to the useFetchBlogs function work.

Embedding Plotly graph in pytest report

I’m trying to embed a Plotly graph in a pytest-html report. To do it, a plotly.Figure is generated during the test execution, and then inserted in the pytest report in the pytest_runtest_makereport (see API reference here).
Bellow, the code of this hook:

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    if call.when == 'call':
        extras = getattr(report, 'extras', [])
        c = item.user_properties[0].to_html(full_html=False, div_id='my_plot', include_plotlyjs='cdn', include_mathjax='cdn')
        extras.append(pytest_html.extras.html("<div>Additional HTML 1</div>"))
        extras.append(pytest_html.extras.html(c))
        extras.append(pytest_html.extras.html("<div>Additional HTML 2</div>"))
        report.extras = extras

Now, when opening the report in Chrome, the plot is not rendered, but seems to be present in the generated HTML report, as well as the Additional HTML 1 and Additional HTML 2 placeholders:
enter image description here

One way to get things working would be to generate an image of the plot and embedding it in the report, but since the plots are quite complex, I would really keep it interactive in order to be able to analyze specific portions of the dataset.

I’m not a specialist of web technologies, so any help would be highly appreciated! 🙂