How to set flag_keep_screen_on from javascript

I’d like to enable or disable the screen_on feature from JAvascript inside the webview.

This is how I tried to do it

@JavascriptInterface
fun setScreenOn(screenOn: Boolean) {
    val window = m_Activity.window
    if (screenOn) {
        Log.d("screen", "addFlag")
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    } else {
        Log.d("screen", "clearFlag")
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}

Unfortunately this gives me a Java exception.

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Expected: main Calling: JavaBridge
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:11023)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:2473)
at android.view.View.requestLayout(View.java:28020)
at android.view.View.setLayoutParams(View.java:20530)
at android.view.WindowManagerGlobal.updateViewLayout(WindowManagerGlobal.java:464)
at android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:165)
at android.app.Activity.onWindowAttributesChanged(Activity.java:4364)
at android.view.Window.dispatchWindowAttributesChanged(Window.java:1323)
at com.android.internal.policy.PhoneWindow.dispatchWindowAttributesChanged(PhoneWindow.java:3193)
at android.view.Window.setFlags(Window.java:1309)
at android.view.Window.clearFlags(Window.java:1283)

Only the original thread that created a view hierarchy can touch its views. Does this mean that it is not possible to change FLAG_KEEP_SCREEN_ON from Javascript? Or is there a way to work around this?

Javascript Test File giving JSDOM TypeError: Cannot convert undefined or null to object

I have a VanillaJS project that has a test.js file. While running the file, it is giving me this error

  ● Test suite failed to run

    TypeError: Cannot convert undefined or null to object
        at Function.getPrototypeOf (<anonymous>)

      1 | import {fireEvent, getByTestId} from "@testing-library/dom"
      2 | import "@testing-library/jest-dom/extend-expect"
    > 3 | import jsdom, {JSDOM} from "jsdom"
        | ^
      4 | import path from "path"
      5 |
      6 | const BASE = path.resolve(__dirname, "../src");

      at Object.getPrototypeOf (node_modules/jsdom/lib/jsdom/living/generated/utils.js:34:39)
      at Object.require (node_modules/jsdom/lib/api.js:11:18)

This was not happening a week ago I guess. It started showing up randomly. Here is a portion of test file that is getting executed.

import {fireEvent, getByTestId} from "@testing-library/dom"
import "@testing-library/jest-dom/extend-expect"
import jsdom, {JSDOM} from "jsdom"
import path from "path"

const BASE = path.resolve(__dirname, "../src");

let virtualConsole
let dom, body

describe("stack operation test", function () {
  beforeEach(async () => {
    virtualConsole = new jsdom.VirtualConsole();
    virtualConsole.on("error", console.error);
    dom = await JSDOM.fromFile(`${BASE}/index.html`, {
      runScripts: "dangerously",
      resources: "usable",
      pretendToBeVisual: true,
      virtualConsole
    })
    await loadDom(dom)
    body = dom.window.document.body
  })

  beforeEach(() => {
    jest.spyOn(dom.window, 'alert').mockImplementation(() => {
    })
  })

  it("Clicking on the push button should push the item to the bottom of the stack board", async function () {
    const input = getByTestId(body, "input")
    await typeText(input, "item1")
....
....
....
....

For reference, here is the package.json and jest.config.json

 "scripts": {
    "prestart": "npm install",
    "build": "webpack --config webpack.config.js",
    "pretest": "npm install && npm run build",
    "start": "node app.js",
    "test": "jest --ci --testResultsProcessor=jest-junit"
  },
  "devDependencies": {
    "@babel/core": "^7.21.8",
    "@babel/preset-env": "^7.21.5",
    "@testing-library/dom": "^9.2.0",
    "@testing-library/jest-dom": "^5.16.5",
    "babel-jest": "^29.5.0",
    "css-loader": "^6.7.3",
    "jest": "^29.5.0",
    "jest-junit": "^16.0.0",
    "jsdom": "^22.0.0",
    "request": "^2.88.2",
    "style-loader": "^3.3.2",
    "webpack": "^5.82.0",
    "webpack-cli": "^4.0.4",
    "webpack-dev-middleware": "^6.1.0",
    "webpack-hot-middleware": "^2.25.3"
  },
  "dependencies": {
    "express": "~4.18.2",
    "h8k-components": "^1.0.0",
    "h8k-design": "^1.0.16",
    "jest-environment-jsdom": "^29.5.0",
    "regenerator-runtime": "^0.13.11"
  }
module.exports = {
    clearMocks: true,
    setupFilesAfterEnv: ['regenerator-runtime/runtime'],
    transformIgnorePatterns: [
        "/node_modules/(?!(jsdom)/)",
    ],
    testPathIgnorePatterns: [
        "/node_modules/",
    ],
    useStderr: true
};

FYI: I have tried upgrading the version of JSDOM, it is not working.

Custom Marker not showing on API Maps Static

I currently use the API Maps Javascript and I wanted to migrate to API Maps Static.
I have a problem with the static API : I can’t seems to make the custom marker to work.

Here is the final url I call : https://maps.googleapis.com/maps/api/staticmap?size=1600×450&zoom=4&scale=2&center=47.1376,4.8137&markers=icon:http%3A%2F%2Fsgl-immo.com%2F%2Fapp%2Fthemes%2FSGL-immo%2Fimg%2Fmap-marker.png%7C44.84173915519152,-0.5772633994775626&markers=icon:https%3A%2F%2Fsgl-immo.com%2F%2Fapp%2Fthemes%2FSGL-immo%2Fimg%2Fmap-marker.png%7C45.75857162475586,4.834653377532959&markers=icon:https%3A%2F%2Fsgl-immo.com%2F%2Fapp%2Fthemes%2FSGL-immo%2Fimg%2Fmap-marker.png%7C48.8658893,2.334566&markers=icon:https%3A%2F%2Fsgl-immo.com%2F%2Fapp%2Fthemes%2FSGL-immo%2Fimg%2Fmap-marker.png%7C43.6521001,1.4356895&key=[KEY_ID]&map_id=[MAP_ID]

I tried to define the marker only one time, I tried to use http instead of https (but I think the https not supported was for an older version ?), but I always have the default marker showing up on my map.

Is it because I use the cloud style api (map id) ? Or am I missing something else ?

the result

Remove leading zeros data from serial port by javascript/jquery [duplicate]

How to remove leading zero and kg from code with javascript or jquery?
from 0000140kg to 140? thanks u…

Code:

const serialResultsDiv = document.getElementById("serialResults");
async function appendToTerminal(newStuff) {
    serialResultsDiv.innerHTML += newStuff;
    if (serialResultsDiv.innerHTML.length > 10) serialResultsDiv.innerHTML = 
serialResultsDiv.innerHTML.slice(serialResultsDiv.innerHTML.length - 10);

enter image description here

Error: invariant expected layout router to be mounted when running a nextjs app

I bootstrapped a nextJs project using nxp create-next-app-@latest and I keep getting this error when I run the project

Next.js (15.0.4) out of date (learn more)

Unhandled Runtime Error

Error: invariant expected layout router to be mounted

I tried using nextJs version 14 and I get this error Application error: a client-side exception has occurred (see the browser console for more information).. I believe it is from the same source, just different error messages

NOTE: NO FILE WAS EDITED. THE FILES ARE THE SAME AS WHEN THE ONES GENERATED BY nxp create-next-app-@latest COMMAND

I tried creating a nextJs app with different versions, I was expecting the code to run successfully and display the boilerplate.

Using MutationObserver to detect changes that are undone

I am currently working on a user interface to detect changes for different areas of concern. The UI looks as depicted below

enter image description here

“Partition 1” can be changed, as it ranges from Partitions 1-8. I have an onchange event-handler which saves the selected inputs (switches which are turned “ON”, from A-E) into an object, if the partition is changed. If the partition is changed, the inputs are reset to the “OFF” position. However, if a previously-selected partition is selected again, its inputs which were turned “ON”, will be switched “ON” automatically, showing one the selected inputs. As shown below, if inputs are selected for Partition-1, and then Partition-2 is selected and its inputs are selected and then reverted back to Partition-1, which ever inputs were selected for Partition-1 will be automatically switched on.

enter image description here
enter image description here

To monitor the changes in the DOM, I am using a mutationObserver, as follows:

const cont1 = new MutationObserver(entries => {
  gen_changes(entries, "column1");
})

const p_cont1 = document.querySelector(".element_switches");

cont1.observe(p_cont1, {attributeFilter: ["checked"], attributeOldValue:true, childList:true, subtree: true});

Where, element_switches is a div enclosing all these switches, while monitoring their checked attribute, and “column1” is the container enclosing the heading and inputs.

However, I have encountered an issue where, if the same switches are checked for 2 partitions, e.g. Partition-1 and Partition-2 respectively, and then unchecked for Partition-1, the mutationObserver does not fire when the switches for Partition-2 are unchecked.

This makes sense for the mutationObserver, but what would be the work-around for this?

Change/Edit text from a Framer Website that i exported

OK so I have been working on a framer website and I wanted to convert it into HTML. I was able to do it using a no code tool that. This is the website that I use to convert my framer website into HTML content: nocodexport It actually did a good job of taking that framer website and creating an exact replica of what it would look like using HTML. But like all things tech related, it has its own problems.

The problem that I’m facing with this converted HTML code is that I cannot edit any of the text in that thing. so for example if i have an H1 tag that says “welcome to our website” and want to change the text to say something like leave our website. I can do it on the HTML side of the code, but previewing it on the browser won’t let me see the text edit that I made. It just defaults back to whatever was there. So I’m not really like an in depth person when it comes to HTML and framer related things, but I pretty much think that this should be possible, right?

So my logical conclusion when it comes to what my problem is, is that there is some kind of JavaScript code that is injecting content into the website. so i have attached the complete HTML code of my index.html file and any help would be totally appreciated. So really like what am I missing? I just don’t get it. Since stackoverflow is not going to let me post the whole code contents because it is super huge, I’m just going to put in a Github link that has the index.html file that you guys can take a look at.
index.html file

Crestron CH5 HTML SIMPL – How to add events after connection?

After a connection has been made with Crestron’s WebXPanel library I want to be able to immediately call a function after that gets the state of a symbol.

The problem unfortunately cant be fixed by DOMContentloaded, as Crestron WebXPanel library gets loaded in after the DOM is initialized. Meaning CrComLib.getState will always return null.

 document.addEventListener("DOMContentLoaded", () => {
let lang = CrComLib.getState('s','Settings.Language.current');

console.log('Language current: ',lang);
    setTimeout(() => {}, 300);
});

example

I could delay a function in DOMContentLoaded by X amount of time, but making a connection takes varying time and isn’t exactly the answer I’m looking for.

I also am attempting to use Ethernet Offline Manager to get a response but I didn’t get very far as I’d still be walking against the same problem.

ethernet_offline_manager_symbol

How can i show or hide an Image element if property is null in array map from returned array in NextJS?

return (
<Container maxWidth="desktop">
  <Typography variant="h1" sx={{ mb: 10 }}>
    Blog
  </Typography>
  <Stack gap={5} useFlexGap>
    {articles.map((article: Article) => (
      <Box key={article._id} sx={{ display: "flex", gap: 3 }}>
        <Box
          sx={{
            position: "relative",
            aspectRatio: "16/9",
            flexShrink: 0,
            width: "30%",
          }}
        >
          <NextImage
                src={article.mainImage.url}
                alt={article.title}
                placeholder="blur"
                blurDataURL={
                  article.mainImage?.metadata?.lqip?.toString() ?? ""
                }
                fill
                style={{
                  objectFit: "cover",
                }}
          />
        </Box>
        <Box>
          <Typography variant="h2" sx={{ mb: 2 }}>
            <Link
              href={`/blog/${article.slug}`}
              component={NextLink}
              underline="hover"
            >
              {article.title}
            </Link>
          </Typography>
          <Typography variant="body2" sx={{ mb: 2 }}>
            By: {article.author}
          </Typography>
          <Typography variant="body2">{article.excerpt}</Typography>
        </Box>
      </Box>
    ))}
  </Stack>
</Container>

);

Sample Data Returned:

[
{
excerpt: “omitted”,
mainImage: null,
categories: null,
_id: ‘3453’,
_createdAt: ‘2024-12-11T16:39:29Z’,
title: ‘omitted’,
slug: ‘omitted’,
author: ‘omitted’
},
]

As you can see, the property “mainImage” in the array is null and it gives me the error:

Error: Cannot read properties of null (reading ‘url’)

I wanted to show or hide the Image element if the mainImage property in the array is null.

Puppeteer button click ISSUE: node is either not clickable or not an element

I am using a script where we have a popup window and confirm button appears with xpath the selector is ok the script runs perfectly fine in local environment but throws this error on a virtual machine run on DigitalOcean’s droplet that the button is not clickable, it leaves or has a stale reference error I am not well versed with puppeteer can anyone recommend what to do here

const connectButton = await popupPage.waitForSelector('::-p-xpath(//button[contains(., "Connect")])', { timeout: 20000 });
if (connectButton) {
  console.log('Connect button found.');
  await connectButton.evaluate(button => button.scrollIntoView());
  await connectButton.click();
  console.log('Connect button clicked.');
  await delay(5000);
} else {
  throw new Error('Connect button not found or not interactable.');
}

The error here comes as

Connect button found but not clickable.

I tried reading this resource too but couldn’t figure out and update my script sometimes I even find error with evaluate function is it that it is on page object rather than element?

https://github.com/puppeteer/puppeteer/issues/10072

Refocus current window after new window loaded in JavaScript

I have a function that opens a pdf for the customer in another window:

const loadWindow = (windowFeatures: string, id: string, pdf: string): void => {
    evidenceWindow = pdf == File.MIME_TYPE ? window.open(
        `/transactions/matching_evidence/${id}#toolbar=0,view=FitH`,
        File.PDF,
        windowFeatures,
    ) : window.open(
        `/transactions/matching_evidence/${id}`,
        File.IMAGE,
        windowFeatures,
    )

    if (evidenceWindow !== null) {
        evidenceWindow.onload = () => {
            localStorage.setItem(GeneralLocalStorateItems.EVIDENCE_WINDOW_LOADED, "true")
            evidenceWindow!.onbeforeunload = () => {
                savePositionToStorage({ "top": evidenceWindow!.screenY, "left": evidenceWindow!.screenX, "height": evidenceWindow!.innerHeight, "width": evidenceWindow!.innerWidth })
                localStorage.setItem(GeneralLocalStorateItems.EVIDENCE_WINDOW_LOADED, "false")
            }
        }

        monitorWindow();
    }

}

Now I have a filter to filter invoices.
If this is happening, this function will be fired.
Then, the first invoice will be opened in a new window.
The problem that occurs is that the new Windows is now the focus.

I have 2 EventHandler to save the current active Element (since there are multiple ways to change the Invoice, not only by filtering) and refocus the element.

window.addEventListener("blur", () => {
    // Save the active element when the tab loses focus
    activeElement = document.activeElement as HTMLElement | null;
});


window.addEventListener("focus", () => {
    // Reapply focus to the saved active element when tab regains focus
    activeElement?.focus();
});

If I tab back into the Window, everything is fine and the correct Element is focused.
But I don’t want the user to lose focus whenever they filter invoices.
So is there a way to re-focus the last window?
The browser would be Chrome.

Edit:
Maybe I can do something to simulate an “alt+tab” user input in the widow onload?

How to customize multiselect input in Laravel to show option names or number of selected options?

I am using a multiselect dropdown in a Laravel project, and I need to customize its behavior. Specifically, I want the input field to show the following:

  1. If fewer than 4 options are selected, display the names of the selected options in the input field (e.g., “Option 1, Option 2”).

  2. If more than 3 options are selected, display a summary like “X selected” (e.g., “4 selected”).

Here’s the HTML code I’m using for the multiselect:

<select class="multiselect @error('age_group_id') is-invalid @enderror" placeholder="Select event for" name="age_group_id[]" id="age_group_id" multiple>
@foreach ($age_groups as $ag)
    <option value="{{ $ag->id }}" {{ in_array($ag->id, old('age_group_id', ($is_update ? $event->age_group_id : []))) ? "selected" : "" }}>
        {{ $ag->name }}
    </option>
@endforeach

I’m using the Bootstrap Multiselect (or Select2, if that’s your case) library, and I want to ensure the following behavior:

  • When fewer than 4 options are selected, display their names.
  • When 4 or more options are selected, show something like “X selected” (e.g., “5 selected”).

I’ve tried modifying the buttonText or templateSelection functions in the multiselect configuration, but I’m not sure how to implement this properly.

Can anyone provide an example or solution to help me achieve this behavior?

Expected Behavior:

  • With 2 options selected: “Option 1, Option 2”
  • With 5 options selected: “5 selected”

Additional Information:

  • I’m using Laravel, but I believe this is more related to the JavaScript configuration of the multiselect library.
  • Any help on customizing the multiselect input behavior would be appreciated!

Checking when a request made by window.open() finished

I have a backend URL which returns a download response to download a PDF file. The URL is called by clicking a button which then uses window.open() to fetch the URL:

let downloadUrl = '/download-pdf';
window.open(
  `${downloadUrl}`,
  '_self'
);

I want to add a loading animation to the download button after the user clicks it, so I need to know when the response finished

Is it even possible to track it when using window.open()? If so, how?
And if not – is there another way I can emulate this window.open() and be able to track the response?

How to ensure background image covers entire page in PDF?

I am using the html2pdf.js library in my Node.js application to generate a multi-page PDF from HTML content. The content is generated dynamically and displayed in a #slideContainer div. I want to set a background image that covers the entire page (including areas without HTML content) for each page of the PDF.

Current Setup

document.getElementById("generatePdfButton").addEventListener("click", () => {
  // Temporarily show all slides
  slides.forEach((slide) => {
    slide.classList.add("active");
  });

  const pdfContent = document.getElementById("slideContainer");
  const options = {
    margin: [0.5, 0.5, 0.5, 0.5],
    filename: "XXXXX",
    image: {
      type: "jpeg",
      quality: 0.98
    },
    html2canvas: {
      scale: 2,
      useCORS: true
    },
    jsPDF: {
      unit: "in",
      format: "a4",
      orientation: "landscape"
    },
    pagebreak: {
      mode: ["avoid-all", "css", "legacy"]
    },
  };

  html2pdf()
    .set(options)
    .from(pdfContent)
    .save()
    .then(() => {
      // Revert slides back to their original state
      showSlide(currentSlide);
    });
});
#slideContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* Center slides vertically */
  min-height: 100vh;
  /* Ensure the container takes at least the full height of the viewport */
  overflow: auto;
  /* Allow scrolling if content overflows */
}

.slide {
  display: none;
  flex-direction: column;
  align-items: center;
  /* Center content horizontally */
  justify-content: center;
  /* Center content vertically */
  width: 80%;
  max-width: 800px;
  background: url("/images/background.jpg") no-repeat center center;
  background-size: cover;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px 0;
  /* Add some space between slides */
  page-break-inside: avoid;
  /* Avoid page breaks inside slides */
}
<div id="slideContainer">
  <div class="slide">
    <h1>Title</h1>
    <p>Content here...</p>
  </div>
</div>
<button id="generatePdfButton">Generate PDF</button>

Issue:

The background image does not cover the entire page in the PDF. It only appears where the HTML content exists, leaving blank spaces on the rest of the page.

Desired Outcome:
I want the background image to span the entire page (including areas without HTML content) for every page of the PDF.

Sample Download

Question:

How can I ensure that the background image covers the full dimensions of each page in the generated PDF using html2pdf? Is there a workaround for html2pdf’s limitations, or am I missing something in my implementation?

Any guidance or examples would be appreciated!

i am unable to sync the seekbar with the audio when the audio is paused

I am trying to sync the seekbar with the currentime of the audio but it works well the audio is playing but do not work when the audio is paused, how can i fix it.

audios.forEach((aud) => {
aud.addEventListener("timeupdate", () => {
    if (!aud.paused && currentAudio === aud) {
        let audiodur = aud.duration;
        let currtime = aud.currentTime;

        // Calculate duration and current time in minutes and seconds
        const min = Math.floor(audiodur / 60).toString().padStart(2, '0');
        const sec = Math.floor(audiodur % 60).toString().padStart(2, '0');
        const min2 = Math.floor(currtime / 60).toString().padStart(2, '0');
        const sec2 = Math.floor(currtime % 60).toString().padStart(2, '0');

        // Update the duration display
        document.querySelector(".playbutton .duration").innerText = `${min2}:${sec2}/${min}:${sec}`;

        let progress = progress_bar.children[0];
        progress.style.width = Math.floor((currtime / audiodur) * 100) + "%";

        progress_bar.onclick = (e) => {
            aud.currentTime = ((e.offsetX / progress_bar.offsetWidth) * aud.duration);
        }
    }
});

});