how to send data from a form to my database through a post method

This is my html where i have the form

enter image description here

this is my api:

@app.route('/productos', methods=['POST'])
def registrar_producto():
    try:
        cursor = conexion.connection.cursor()
        sql = """INSERT INTO productos (idproductos, productos_name, productos_descripcion, productos_precio) 
        VALUES ('{0}', '{1}', '{2}', {3})""".format(request.json['idproductos'], request.json['productos_name'], request.json['productos_descripcion'], request.json['productos_precio'])
        cursor.execute(sql)
        conexion.connection.commit() # confirma la accion de agregar
        return jsonify({"Mensaje":"Producto registrado correctamente"})
    except Exception as ex:
        return jsonify({"Error": 'Este producto ya existe'})

this is my vue app:

async nuevoProducto() {
            try {
                const response = await fetch('http://127.0.0.1:5000/productos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.nuevoProducto)
                });
                if (response.ok) {
                    console.log('Producto agregado con éxito.');
                    this.obtenerProductos();
                    this.nuevoProducto = {
                        idproductos: '',
                        productos_name: '',
                        productos_descripcion: '',
                        productos_precio: 0,
                    };
                } else {
                    console.error('Error al agregar el producto:', response.statusText);
                }
            } catch (error) {
                console.error('Error al agregar el producto:', error);
            }
        }
    },

using Thunder Client it works perfectly but if i try to add this data through the form it doesnt

enter image description here

i expect the data to be sent to the db using the form

How to display AdMob’s rewarded ad in webview via JavaScript in Android?

I’m planning to display a admob rewarded ad by a button click in a webview via javascript.
The ad runs but a black screen is displayed. That is, the listener onAdLoaded() and onAdShowedFullScreenContent() are both executed, but it does not display an ad and only displays a black page.
In addition, I also use test tokens and when I put the ad display command in the onAdLoaded() listener, the ad is displayed well.
Only when I call with javascript, I have the black page problem.

javascript code:

function kurosh(){
            JSInterface.getData("hashcode");
        }

android code:

public class JSInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JSInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void getData(String hashCode) {
            Hashcode = hashCode;
            showRewardAd();
        }
    }
wv.addJavascriptInterface(new JSInterface(c), "JSInterface");
private void initializeMobileAdsSdk() {
        /*if (isMobileAdsInitializeCalled.getAndSet(true)) {
            return;
        }*/

        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(c, "ca-app-pub-3940256099942544~3347511713");
        /*List<String> testDeviceIds = Arrays.asList("EE3D38ABAA050D0967ABE3F07EDFA862");
        RequestConfiguration configuration =
                new RequestConfiguration.Builder().setTestDeviceIds(testDeviceIds).build();
        MobileAds.setRequestConfiguration(configuration);*/

        // Load an ad.
        loadRewardedAd();
    }

private void loadRewardedAd() {
        if (rewardedAd == null) {
            isLoading = true;
            AdRequest adRequest = new AdRequest.Builder().build();
            RewardedAd.load(
                    this,
                    "ca-app-pub-3940256099942544/5224354917",
                    adRequest,
                    new RewardedAdLoadCallback() {
                        @Override
                        public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                            // Handle the error.
                            Log.d("ERROR LOG REWARD", loadAdError.getMessage());
                            rewardedAd = null;
                            comment.this.isLoading = false;
                            Toast.makeText(comment.this, "onAdFailedToLoad", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                            comment.this.rewardedAd = rewardedAd;
                            Log.d("ERROR LOG REWARD", "onAdLoaded");
                            comment.this.isLoading = false;
                            Toast.makeText(comment.this, "onAdLoaded", Toast.LENGTH_SHORT).show();
                            //showRewardAd();
                        }
                    });
        }
    }

public void showRewardAd(){
        runOnUiThread(new Runnable() {
            public void run() {
                showRewardedVideo();
            }

        });
    }
    public void showRewardedVideo() {
        if (rewardedAd == null) {
            Log.d("TAG", "The rewarded ad wasn't ready yet.");
            return;
        }
        rewardedAd.setFullScreenContentCallback(
                new FullScreenContentCallback() {
                    @Override
                    public void onAdShowedFullScreenContent() {
                        // Called when ad is shown.
                        Log.d("ERROR LOG REWARD", "onAdShowedFullScreenContent");
                        Toast.makeText(comment.this, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                    }

                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        // Called when ad fails to show.
                        Log.d("ERROR LOG REWARD", "onAdFailedToShowFullScreenContent");
                        // Don't forget to set the ad reference to null so you
                        // don't show the ad a second time.
                        rewardedAd = null;
                        Toast.makeText(comment.this, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                    }

                    @Override
                    public void onAdDismissedFullScreenContent() {
                        // Called when ad is dismissed.
                        // Don't forget to set the ad reference to null so you
                        // don't show the ad a second time.
                        rewardedAd = null;
                        Log.d("ERROR LOG REWARD", "onAdDismissedFullScreenContent");
                        Toast.makeText(comment.this, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT)
                                .show();
                        //if (googleMobileAdsConsentManager.canRequestAds()) {
                            // Preload the next rewarded ad.
                        comment.this.loadRewardedAd();
                        comment.this.adShowFinished();

                        //}
                    }
                });
        Activity activityContext = comment.this;

        rewardedAd.show(activityContext, new OnUserEarnedRewardListener() {
            @Override
            public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                // Handle the reward.
                Log.d("TAG", "The user earned the reward.");
                adstatus = true;
            }
        });
    }

enter image description here

whats problem?

I tried different methods and changed the parameters, but the result was still the same black screen. Of course, it was shown once, but it was not shown again

Regarding responsiveness of website for tablet screen and desktop screen

I was creating a sample page with the material ui in react functional component, so my component is looking fine for mobile devices, and looking fine for tablet devices till 900px, so I am not able to manage responsiveness properly for device width above 900px and for 1200px and large devices like 1800px+, if anyone have any idea then please let me know, i’m tired of searching here and there but no luck, below is the component code and css code then please help me

import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import { Button, Grid, Typography } from '@mui/material';
import Checkbox from '@mui/material/Checkbox';
import './style.scss';
import { handleEmailChange, handlePasswordChange } from '../../utils';
import AppLogo from '../../component/AppLogo';

function Login() {
  const [email, setEmail] = useState('');
  const [isValidEmail, setIsValidEmail] = useState(true);

  const [password, setPassword] = useState('');
  const [isValidPassword, setIsValidPassword] = useState(true);

  const onEmailChange = (event) => {
    const inputEmail = event.target.value;
    if (inputEmail.length === 0 || inputEmail === undefined) {
      setIsValidEmail(true);
      setEmail('');
    } else {
      handleEmailChange(inputEmail, setEmail, setIsValidEmail);
    }
  };

  const onPasswordChange = (event) => {
    const inputPassword = event.target.value;
    if (inputPassword === '' || inputPassword === undefined) {
      setIsValidPassword(true);
      setPassword('');
    } else {
      handlePasswordChange(inputPassword, setPassword, setIsValidPassword);
    }
  };
  return (
    <div className='mainStyle'>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={12} md={12} lg={6} xl={6}>
          <AppLogo />
        </Grid>
        <Grid item xs={12} sm={12} md={12} lg={6} xl={6} className='login_content'>
          <div className='input_style'>
            <Grid item xs='auto' sm='auto' md='auto' lg='auto' xl='auto'>
              <TextField
                color='success'
                error={!isValidEmail}
                label='E-mail address*'
                variant='outlined'
                value={email}
                onChange={onEmailChange}
                fullWidth
              />
              {!isValidEmail && (
                <Typography className='error_style'>
                  Please enter a valid email address.
                </Typography>
              )}
            </Grid>
            {/* <Grid item xs={12} sm={12} md={12} lg={12} xl={12}> */}
            <Grid item xs={12} sm='auto' md='auto' lg='auto' xl='auto'>
              <TextField
                color='success'
                error={!isValidPassword}
                label='Password*'
                variant='outlined'
                value={password}
                type='password'
                onChange={onPasswordChange}
                fullWidth
              />
              {!isValidPassword && (
                <Typography className='error_style'>
                  Password must be 8-15 characters, alphanumeric, with at least
                  one special character and one uppercase letter.
                </Typography>
              )}
            </Grid>
          </div>
          <a className='forgot_password_style' href='https://www.google.com' target='_blank' rel='noreferrer'>
            Forgot Password?
          </a>
          <div className='terms_and_condition_style'>
            <Checkbox />
            <span className='agreement_style'>
              I agree to the &nbsp;
              <a className='T_C_style' href='https://www.google.com' target='_blank' rel='noreferrer'>
                Terms and Conditions.
              </a>
            </span>
          </div>
          {/* <Grid xs={12} sm={12} md={12} lg={12} xl={12}> */}
          <Button variant='outlined' className='button-style' fullWidth>
            Sign In
          </Button>
          {/* </Grid> */}
          <a className='dont_have_account_style' href='https://www.google.com'>
            I do not have an account. Sign Up Now.
          </a>
        </Grid>
      </Grid>
    </div>
  );
}

export default Login;

below is the css code

.mainStyle{
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin: 0 auto;
  margin-top: 8%;
  padding-left: 3%;
  @media screen and (min-width: 1200px) {
    top: 49%;
  }
  @media (min-width: 600px) and (max-width: 1199px){
  margin-top: 20%;
  padding-left: 4%;
  }
}
// .login_content{
//   width: 50%;
// }
.input_style{
  width: 60%;
  margin-top: 5%;
  margin-left: 5%;
  @media (min-width: 600px) and (max-width: 1199px){
    margin-top: 5%;
    margin-left: 11%;
  }
  @media (min-width: 1200px){
    margin-top: 17%;
    width: 70%;
  }
}
.forgot_password_style{
  color: #4FD333;
  position: relative;
  padding-left: 53%;
  display: flex;
  width: 45%;
  font-size: 16px;
  @media (max-width: 600px){
    margin-left: calc(100% - 95%);
    width: 40%;
  }
  @media (min-width: 600px) and (max-width: 899px){
    margin-left: calc(50% - 53%);
    width: 45%;
  }
  @media (min-width: 900px) and (max-width: 1199px){
    margin-left: calc(50% - 55%);
    width: 45%;
  }
}
.terms_and_condition_style{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 10%;
  margin-left: calc(2vw + 18%);
  width: 60%;
  margin-left: 25%;
  @media (max-width: 600px){
    margin-left: 4%;
    margin-top: 45%;
    width: auto;
  }
  @media (min-width: 900px) and (max-width: 1199px){
    margin-left: 30%;
  }
}
.agreement_style{
  flex: 1;
  font-family: 'Montserrat', sans-serif;
  font-size: 16px;
  width: 230px;
  letter-spacing: 0px;
  text-align: left;
  @media (max-width: 600px){
    font-size: 16px;
  }
}
.T_C_style{
  color: #4FD333;
  display: inline;
}
.error_style{
  color: #B00020;
  margin-bottom: 5%;
  width: 73vw;
  font-family: 'Montserrat', sans-serif;
  font-weight: bold;
  font-size: 16px;
}
.dont_have_account_style{
  color: #4FD333;
  display: flex;
  margin-left: 27%;
  font-size: 16px;
  width: 60%;
  font-weight: 700;
  opacity: 1;
  margin-bottom: 3%;
  @media (max-width: 600px){
    margin-left: 10%;
    width: 80%;
  }
  @media (min-width: 900px) and (max-width: 1199px){
    margin-left: 33%;
    width: 40%;
  }
}
.button-style{
  width: auto;
  display: flex;
  position: relative;
  margin-left: 24%;
  border: 1px solid black;
  margin-bottom: 10px;
  background-color: #C9F2C0 !important;
  @media screen and (max-width: 600px) {
    // width: 85%;
    margin-left: 6%;
  }
  @media (min-width: 600px) and (max-width: 899px){
    // width: 43%;
    margin-left: calc(2vw + 24%);
  }
  @media (min-width: 900px) and (max-width: 1199px){
    // width: 30%;
    margin-left: calc(2vw + 29%);
  }
}

I want something like for mobile devices every component will be line by line and the same for tablet screen as well but when we select tablet screen then input and button width should also increase as the width is increased, for laptop logo should be on left side and all content should be write side properly aligned.
How can I achieve the above functionality, I’m a beginner in material UI. Please help me with this… Thanks in advance.

Vue Js 2 provide cannot be updated in Parent

I’m trying to use the provide functions in Vue.js 2.7 and i want to update one of the props through an async function but it doesn’t update the injection in the children

Parent.vue

<template>
    <Child />
</template>

<script>
export default {
    provide(){
        return {
            typesTabs: null,
            instanceTypeToAdd: null,
            buttonInstanceTypeToAdd: null,
            updateProvidedPropValue: this.updateProvidedPropValue
        }
    },
    mounted(){
       this.fetchInstances()
    },
    methods: {
        updateProvidedPropValue(propName, value) {
            this[propName] = value
        },
        async fetchInstances() {
            axios.get().then(() => {
                this.typesTabs =
                    JSON.parse(JSON.stringify(res.data.expense_income_type_consts))
            })
        }
    }
}
</script>

Child.vue

<template> 
    <div 
        v-for="tab in typesTabs" 
        @click="updateProvidedPropValue('instanceTypeToAdd', tab)"
    > 
        {{ tab.name }} 
    </div>
</template>

<script>
    export default {
        inject: ['typesTabs', 'instanceTypeToAdd', 'updateProvidedPropValue']
    }
</script>

while the updateProvidedPropValue works properly IF i give the typesTabs object hard coded, when it’s loading asynchronously the typesTabs doesn’t contain anything so i can’t change the instanceTypeToAdd.

I tried to console.log(this.typesTabs) in Parent.vue right after the axios request and it’s filling the prop (typesTabs) propperly, but does not update to show content in children.

Algolia filtering compare two strings with greater or less than

I am using Algolia for a web application using the JS SDK and I am trying to filter by
a string value using comparison operators like >, <, >=, etc…

I was expecting it to be filtering the strings by ASCII value like “ac” < “ba”

I tried solving this by using the following code:

return index.search(query, {
   filters: "myId <= 'ba'"
});

Expecting it to return only records with IDs like ‘acd’, ‘ax’, ‘ba’, …

But I got the error:
filters: Unexpected token string(ba) expected numeric at col 13

My question is now: Is this even supported by Algolia or is there any workaround to achieve this?

Thank you in advance.

PDF: A button to add a row of text fields on fillable form

The original thread:
https://community.adobe.com/t5/acrobat-discussions/have-a-button-in-adobe-acrobat-that-adds-a-row-of-columns-then-adds-another-row-below-it/m-p/14250883#M439889

The script works to create fillable text fields, however I need to limit the number of rows it creates. Below is the javascript:

var myRows = new Array();
var rowCounter = 1;

function addRow() {

if (rowCounter >= 5) {
return;
}

myRows[rowCounter - 1] = "Row" + rowCounter + ".Column1";
myRows[rowCounter] = "Row" + rowCounter + ".Column2";
myRows[rowCounter + 1] = "Row" + rowCounter + ".Column3";
myRows[rowCounter + 2] = "Row" + rowCounter + ".Column4";


var w = 144;
var h = 18;
var wGap = 6;

for (var j = 0; j < 1; j++) {  // Adjust the number of rows per line (here set to 2 for 4 columns)

    var coordinates = [10, 700 + (rowCounter * 24)]; // Adjust the vertical position for each new row
    var afields = [coordinates[0], coordinates[1], coordinates[0] + w, coordinates[1] - h];

    for (var i = 0; i < myRows.length; i++) {
        this.addField(myRows[i], "text", 0, afields);
        afields[0] += (w + wGap);
        afields[2] += (w + wGap);
    }
    rowCounter += -1;
}
}

The button functions under actions: Mouse Up > Execute a Menu Item > ‘Run a javascript’:

addRow();

Right now it seems to create an infinite number of text field and need to limit the rows to at least 5 rows. I would like to also add a button that would delete row(s) if too many is created. Is this possible?

fetch and handleFetch’s event parameter – sveltejs/kit

As per my observations, there are three functions (handle(), handleFetch(), and handleError()) designed to handle fetch requests. Each of these functions accepts an event parameter, which includes a route.id. However, I’ve noticed that the handleFetch() function, while including the route.id parameter, seems to display the route from where the fetch() is called rather than the specific endpoint mentioned in fetch().

for example:

calling fetch from +page.server.js from the url http://localhost:5173/admin/users/123

export const load = async ({ fetch, params }) => {
  const id = params.id;
  const response = await fetch(`/api/users/${id}`);
  const data = await response.json();
  return data;
};

handling fetch from the three functions in +hooks.server.ts:

export const handle: Handle = ({ event, }) => {
  console.log(event.route.id); // expected result: api/users/[id]
  // output result: api/users/[id]
};

export const handleFetch: HandleFetch = ({ event }) => {
  console.log(event.route.id); // expected result: api/users/[id]
  // output result: admin/users/123 --> UGH!!!!
};

export const handleError = ({ event }) => {
  console.log(event.route.id); api/users/[id]
  // output result: api/users/[id]
};

Thank you for your attention to this matter, and I appreciate any insights or guidance you can provide to resolve this discrepancy.

Input not accepting text

I’m working on a chrome extension that allows users to input exact time locations into their video player. It’s a simple overlay that appears over a video frame. It works on Youtube videos (although I still have to deal with periodically ‘losing connection’ with the tab), and does in fact appear over videos in the Spotify player, but I cannot enter text into the input.

To be more specific, the input appears and displays a typing cursor on mouseover. However, the input cannot be focused and the blinking cursor does not appear. No text will appear if I click on the input and begin typing. If I do submit the form, the video’s time input will be set to 0 as I assume the default empty value would be 0 (so, 0 seconds into the video).

The input is z-indexed to the top-most and above the underlying div it’s nested in. There are no changes made to the HTML when injected into the Spotify site, and no error messages in the console.

Previously, the overlay would not appear on top of the video. The issue came from Spotify requiring an id and class name for the HTML element in order to display.

Again, my cursor does in fact change on mouseover. Clicking on the input, however, does not focus the input and I cannot enter text into the input at all.

Code:

There is only one input, with the id “timeInput” and the styling “input_style”.


    console.log("content.js");
    let overlayVisibleBool = false;
    
    // Function to handle overlay display
    function toggleOverlay(overlayVisible) {
      chrome.runtime.sendMessage(
        { command: "checkActiveTab" },
        function (response) {
          if (response && response.isValid) {
            const videoElement = document.getElementsByTagName("video")[0];
            const popup = document.getElementById("rr_overlay");
    
            if (videoElement && popup) {
              const videoRect = videoElement.getBoundingClientRect();
    
              overlayVisible = !overlayVisible;
    
              if (!overlayVisible) {
                console.log(videoRect);
                popup.style.display = "flex";
                popup.style.position = "absolute";
                popup.style.left = videoRect.left + "px";
                popup.style.bottom = videoRect.bottom + "px";
                popup.style.top = videoRect.top + "px";
                popup.style.width = videoRect.width + "px";
                popup.style.height = videoRect.height + "px";
    
                popup.style.zIndex = 9999;
    
                popup.style.justifyContent = "center";
                popup.style.alignItems = "center";
                popup.style.flexDirection = "column";
    
                const timeInput = document.getElementById("timeInput");
                if (timeInput) {
                  timeInput.focus();
                }
              } else {
                // Hide the overlay
                popup.style.display = "none";
              }
            }
          }
        }
      );
    }
    
    window.onresize = function () {
      const videoElement = document.querySelector("video");
      const videoRect = videoElement.getBoundingClientRect();
      const popup = document.getElementById("rr_overlay");
      popup.style.left = videoRect.left + "px";
      popup.style.bottom = videoRect.bottom + "px";
      popup.style.top = videoRect.top + "px";
      popup.style.width = videoRect.width + "px";
      popup.style.height = videoRect.height + "px";
    };
    
    let overlay_style = `
      display: none; 
      position: fixed; 
      top: 0; 
      right: 0; 
      bottom: 0; 
      left: 0; 
      background-color: rgba(0, 0, 0, 0.75);
      clear: both;
    `;
    
    let image_style = `
      width: 200px;
      height: auto;
      margin-top: -50px;
      margin-bottom: -15px;
    `;
    
    let link_logo_style = `
      width: 12px;
      height: auto;
    `;
    
    let input_style = `
      border: 0px solid;
      background-color: transparent;
      color: white;
      font-size: 24px;
      padding: 10px;
      width: auto;
      outline: none;
      font-family: Arial, sans-serif;
      z-index: 99999 !important;
      clear: both;
      position: relative;
    `;
    
    let form_style = `
      display: flex;
      align-items: center;
    `;
    
    let button_style = `
      width: 100px;
      height: 30px;
      line-height: 20px;
      padding: 0;
      border: none;
      background: rgb(255,27,0);
      background: linear-gradient(0deg, rgba(255,27,0,1) 0%, rgba(251,75,2,1) 100%);
      cursor: pointer;
      border-radius: 5px;
      font-size: 12px;
      color: white;
    `;
    
    let link_button_style = `
      width: 30px;
      height: 30px;
      line-height: 20px;
      padding: 0;
      border: none;
      background: rgb(255,27,0);
      background: linear-gradient(0deg, rgba(255,27,0,1) 0%, rgba(251,75,2,1) 100%);
      cursor: pointer;
      border-radius: 5px;
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
    `;
    
    const rr_logo = chrome.runtime.getURL("assets/rrewind.svg");
    const link_logo = chrome.runtime.getURL("assets/link.svg");
    const overlay = **image attached**
    const popupElement = document.createElement("div");
    popupElement.id = "popup_container";
    popupElement.className = "popup_container";
    popupElement.innerHTML = overlay;
    document.body.appendChild(popupElement);
    
    console.log("Plugged in.");
    
    const jumpForm = document.getElementById("jumpForm");
    
    jumpForm.addEventListener("submit", function (e) {
      e.preventDefault();
      console.log("submitting jump");
      manageTime(e);
    });
    
    function manageTime(e) {
      console.log(timeInput);
      chrome.runtime.sendMessage(
        { command: "checkActiveTab" },
        function (response) {
          if (response && response.isValid) {
            const action = e.submitter.value;
            console.log(action);
            if (action === "jump") {
              const timeInput = document
                .getElementById("timeInput")
                .value.split(":");
              console.log(timeInput);
              tl = timeInput.length;
    
              let hoursInput, minutesInput, secondsInput, totalSeconds;
    
              if (tl === 3) {
                hoursInput = parseInt(timeInput[0], 10) || 0;
                minutesInput = parseInt(timeInput[1], 10) || 0;
                secondsInput = parseInt(timeInput[2], 10) || 0;
                totalSeconds = hoursInput * 3600 + minutesInput * 60 + secondsInput;
              } else if (tl === 2) {
                minutesInput = parseInt(timeInput[0], 10) || 0;
                secondsInput = parseInt(timeInput[1], 10) || 0;
                totalSeconds = minutesInput * 60 + secondsInput;
              } else if (tl === 1) {
                secondsInput = parseInt(timeInput[0], 10) || 0;
                totalSeconds = secondsInput;
              } else {
                return;
              }
    
              chrome.runtime.sendMessage({
                command: "jumpToTime",
                time: totalSeconds,
              });
              overlayVisibleBool = false;
              toggleOverlay(overlayVisibleBool);
            } else if (action === "link") {
              const videoElement = document.querySelector("video");
              let totalSeconds = videoElement.currentTime;
              chrome.runtime.sendMessage({
                command: "getLink",
                time: totalSeconds,
              });
            }
          }
        }
      );
    }
    
    document.addEventListener("keydown", function (event) {
      // Check if CTRL + ` is pressed
      if (event.ctrlKey && event.key === "`") {
        console.log("TOGGLE ACTIVATED!");
        overlayVisibleBool = !overlayVisibleBool;
        console.log("overlay: ", overlayVisibleBool);
        toggleOverlay(overlayVisibleBool);
      }
    });

The injected HTML (couldn’t attach the text):
Code snippet.

background.js:


    function getActiveTabId(callback) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs && tabs.length > 0) {
          const tabId = tabs[0].id;
          callback(tabId);
        }
      });
    }
    
    chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
      if (message.command === "checkActiveTab") {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          const isValid = tabs && tabs.length > 0;
          sendResponse({ isValid: isValid });
        });
        return true; // Indicates that sendResponse will be called asynchronously
      }
    });
    
    chrome.runtime.onMessage.addListener(async function (
      message,
      sender,
      sendResponse
    ) {
      getActiveTabId((tabId) => {
        if (message.command === "jumpToTime") {
          console.log("message sent: jumpToTime");
          chrome.scripting.executeScript(
            {
              target: { tabId: tabId },
              func: (time) => {
                const videoElement = document.querySelector("video");
                if (videoElement) {
                  console.log("total time: ", time);
                  videoElement.currentTime = time;
                }
              },
              args: [message.time], // Pass the time parameter
            },
            (result) => {
              if (chrome.runtime.lastError) {
                console.error(
                  "Background script: Error executing script in content script:",
                  chrome.runtime.lastError
                );
              } else {
                console.log(
                  "Background script: Script executed successfully:",
                  result
                );
              }
            }
          );
        } else if (message.command === "getLink") {
          chrome.scripting.executeScript({
            target: { tabId: tabId },
            func: (time) => {
              if (window.location.href.includes("youtube")) {
                const pageUrl = window.location.href
                  .replace("www.", "")
                  .replace("youtube.com", "youtu.be")
                  .replace("watch?v=", "");
                navigator.clipboard.writeText(
                  pageUrl + "?feature=shared&t=" + Math.ceil(time)
                );
              } else {
                const pageUrl = window.location.href;
                navigator.clipboard.writeText(pageUrl);
              }
            },
            args: [message.time],
          });
        }
      });
      return true;
    });

manifest.json:


    {
      "manifest_version": 3,
      "name": "RedbarRewind",
      "version": "1.0.0",
      "description": "Give it a year.",
      "permissions": ["storage", "tabs", "activeTab", "scripting"],
      "host_permissions": ["https://*.youtube.com/watch*", "https://*.spotify.com/*"],
      "action": {
        "default_icon": {
          "16": "assets/rrewind16.png",
          "48": "assets/rrewind48.png",
          "128": "assets/rrewind128.png"
        }
      },
      "background": {
        "service_worker": "background.js"
      },
      "content_scripts": [
        {
          "matches": ["https://*.youtube.com/watch*", "https://*.spotify.com/*"],
          "js": ["content.js"]
        }
      ],
      "web_accessible_resources": [
        {
          "resources": [
            "assets/rrewind.svg",
            "assets/redbarrewind.svg",
            "assets/link.svg"
          ],
          "matches": ["https://*.youtube.com/*", "https://*.spotify.com/*"]
        }
      ],
      "icons": {
        "16": "assets/rrewind16.png",
        "48": "assets/rrewind48.png",
        "128": "assets/rrewind128.png"
      }
    }

The main problem, I’m assuming, lies with a hidden necessity in the HTML or styling that I’m missing. As I mentioned before, the parent div required a class and id in order to appear overlaid on the video, something I’d noticed in the CSS injected by the Spotify styling.

There is also no hint that the input is in any way disabled or readonly in the DOM. It might also be an issue with the CSP (Content Security Policy) although those error pop up in the console regardless of whether the addon is enabled or not. Thank you in advance for any help!

How to conditionally execute javascript code based on the host environment or the debug/release mode of an asp.net core project?

In a ASP.NET Core 3.1 project, I conditionally execute c# code based on the host environment, for example:

if (this.webHostEnvironment.IsProduction())
{
   // execute code only when ASPNETCORE_ENVIRONMENT is not Development
}

Elsewhere #if DEBUG is used to distinguish between debug and release modes:

#if DEBUG
   ...
#else
   ...
#endif

The project also contains javascript code. Is there a way to apply any of the above methods to the javascript code? For example, in the following situation:

class MyClass {
    constructor() {        
        this.checkEvery = 10;        // DEBUG: 30    RELEASE: 10
        this.checkDuration = 'm';    // DEBUG: 's'   RELEASE: 'm'
    }
}

If not, is there any other way to achieve this?

How can I map an audio player in React.JS and Hygraph?

First of all, sorry for my english, it’s not my first langage. Also I’m pretty new to coding so please be patient (and please be as clear as if you where talking to a rubber duck XD).

I’m trying to display mp3 from Hygraphs assets I uploaded. I want to map them so that if anybody add a file later, a new audioplayer will appear on my page.

The thing is my players are all playing the same mp3 even if I have several url, and/or I have errors such as

index.js:41 Uncaught TypeError: Cannot read properties of undefined (reading ‘duration’)

I think it’s because of refs or something like that, but I don’t know how to fix it at all.

My component:

function OnePodcast({ posts }) {
  const listOfPodcasts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Podcasts'));

  // State
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  // References
  const audioPlayer = useRef(); // reference the audioplayer component
  const progressBar = useRef(); // reference the progress bar
  const animationRef = useRef(); // reference the animation

  const onLoadedMetadata = () => {
    setDuration(Math.floor(audioPlayer.current.duration));
  };

  useEffect(() => {
    const seconds = Math.floor(audioPlayer.current.duration);
    setDuration(seconds);
    progressBar.current.max = seconds;
  }, [audioPlayer?.current?.loadedmetadata, audioPlayer?.current?.readyState]);

  const calculateTime = (secs) => {
    const minutes = Math.floor(secs / 60);
    const returnedMinutes = minutes < 10 ? `0${minutes}` : `${minutes}`;
    const seconds = Math.floor(secs % 60);
    const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
    return `${returnedMinutes}:${returnedSeconds}`;
  };

  const togglePlayPause = () => {
    const prevValue = isPlaying;
    setIsPlaying(!prevValue);
    if (!prevValue) {
      audioPlayer.current.play();
      animationRef.current = requestAnimationFrame(whilePlaying);
    }
    else {
      audioPlayer.current.pause();
      cancelAnimationFrame(animationRef.current);
    }
  };

  const whilePlaying = () => {
    progressBar.current.value = audioPlayer.current.currentTime;
    changePlayerCurrentTime();
    animationRef.current = requestAnimationFrame(whilePlaying);
  };

  const changeRange = () => {
    audioPlayer.current.currentTime = progressBar.current.value;
    changePlayerCurrentTime();
  };

  const changePlayerCurrentTime = () => {
    progressBar.current.style.setProperty('--seek-before-width', `${progressBar.current.value / duration * 100}%`);
    setCurrentTime(progressBar.current.value);
  };

  const backThirty = () => {
    progressBar.current.value = Number(progressBar.current.value - 30);
    changeRange();
  };

  const forwardThirty = () => {
    const newTime = audioPlayer.current.currentTime + 30;
    // Needed this to fix the wrong number of secs added to the player
    if (newTime <= duration) {
      audioPlayer.current.currentTime = newTime;
      progressBar.current.value = newTime;
      changePlayerCurrentTime();
    }
  };

  return (
    <Container>
      {listOfPodcasts.map((podcast) => (
        <section className="onePodcast">
          <div className="audioPlayers-block">
            <article className="audioPlayer">
              <h3 className="header">{podcast.node.titre}</h3>
              <RichText
                content={podcast.node.contenu.raw}
              />
              <div className="audioPlayer__player">
                {/* Map to display assets files */}
                {podcast.node.fichier && podcast.node.fichier.map((fichier) => (
                  <audio ref={audioPlayer} src={fichier.url} preload="metadata" onLoadedData={onLoadedMetadata} />
                ))}
                {/* Buttons for desktop */}
                <div className="audioPlayer__player-btn displayNoneMobile">
                  <button type="button" onClick={backThirty} className="audioPlayer__btn"><TbPlayerTrackPrevFilled /> </button>
                  <button type="button" onClick={togglePlayPause} className="audioPlayer__main-btn">
                    {isPlaying ? <TbPlayerPauseFilled /> : <TbPlayerPlayFilled /> }
                  </button>
                  <button type="button" onClick={forwardThirty} className="audioPlayer__btn"><TbPlayerTrackNextFilled /> </button>
                </div>

                <div className="audioPlayer__player-bar">
                  {/* current time */}
                  <div className="audioPlayer__currentTime">{calculateTime(currentTime)}</div>
                  {/* Progress bar */}
                  <div>
                    <input type="range" className="audioPlayer__progressBar" defaultValue="0" ref={progressBar} onChange={changeRange} />
                  </div>
                  {/* duration */}
                  <div className="audioPlayer__duration">{(duration && !Number.isNaN(duration)) && calculateTime(duration)}</div>
                </div>

                {/* Buttons for mobile */}
                <div className="audioPlayer__player-btn displayNoneDesktop">
                  <button type="button" onClick={backThirty} className="audioPlayer__btn"><TbPlayerTrackPrevFilled /> </button>
                  <button type="button" onClick={togglePlayPause} className="audioPlayer__main-btn">
                    {isPlaying ? <TbPlayerPauseFilled /> : <TbPlayerPlayFilled /> }
                  </button>
                  <button type="button" onClick={forwardThirty} className="audioPlayer__btn"><TbPlayerTrackNextFilled /> </button>
                </div>
              </div>
            </article>
          </div>
        </section>
      ))}
    </Container>
  );
}

To be honest, I asked ChatGPT for help since I couldn’t find anything online and here is the last code it proposed (with the same error “Uncaught TypeError: Cannot read properties of undefined (reading ‘duration’)”). Every other solutions it proposed were wrong the same way with a different error in “Cannot read properties of undefined (reading ‘XXX’).
Thank you soooo much for your help!

function OnePodcast({ posts }) {
  const listOfPodcasts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Podcasts'));

  // State
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  // References
  const audioPlayer = useRef(listOfPodcasts.map(() => createRef())); // reference the audioplayer component
  const progressBar = useRef(listOfPodcasts.map(() => createRef())); // reference the progress bar
  const animationRef = useRef(listOfPodcasts.map(() => null)); // initialize with null values

  const onLoadedMetadata = (index) => {
    setDuration(Math.floor(audioPlayer.current[index].current.duration));
  };

  useEffect(() => {
    const seconds = Math.floor(audioPlayer.current[0].current.duration);
    setDuration(seconds);
    progressBar.current[0].max = seconds;
  }, [audioPlayer?.current?.[0]?.loadedmetadata, audioPlayer?.current?.[0]?.readyState]);

  const calculateTime = (secs) => {
    const minutes = Math.floor(secs / 60);
    const returnedMinutes = minutes < 10 ? `0${minutes}` : `${minutes}`;
    const seconds = Math.floor(secs % 60);
    const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
    return `${returnedMinutes}:${returnedSeconds}`;
  };

  const togglePlayPause = (index) => {
    const prevValue = isPlaying;
    setIsPlaying(!prevValue);
    const currentPlayer = audioPlayer.current[index].current;

    if (!prevValue) {
      currentPlayer.play();
      animationRef.current[index] = requestAnimationFrame(() => whilePlaying(index));
    } else {
      currentPlayer.pause();
      cancelAnimationFrame(animationRef.current[index]);
    }
  };

  const whilePlaying = (index) => {
    progressBar.current[index].current.value = audioPlayer.current[index].current.currentTime;
    changePlayerCurrentTime(index);
    animationRef.current[index] = requestAnimationFrame(() => whilePlaying(index));
  };

  const changeRange = (index) => {
    audioPlayer.current[index].current.currentTime = progressBar.current[index].current.value;
    changePlayerCurrentTime(index);
  };

  const changePlayerCurrentTime = (index) => {
    progressBar.current[index].current.style.setProperty('--seek-before-width', `${progressBar.current[index].current.value / duration * 100}%`);
    setCurrentTime(progressBar.current[index].current.value);
  };

  const backThirty = (index) => {
    progressBar.current[index].current.value = Number(progressBar.current[index].current.value - 30);
    changeRange(index);
  };

  const forwardThirty = (index) => {
    const newTime = audioPlayer.current[index].current.currentTime + 30;

    if (newTime <= duration) {
      audioPlayer.current[index].current.currentTime = newTime;
      progressBar.current[index].current.value = newTime;
      changePlayerCurrentTime(index);
    }
  };

  return (
    <Container>
      {listOfPodcasts.map((podcast, index) => (
        <section className="onePodcast" key={index}>
          <div className="audioPlayers-block">
            <article className="audioPlayer">
              <h3 className="header">{podcast.node.titre}</h3>
              <RichText content={podcast.node.contenu.raw} />
              <div className="audioPlayer__player">
                {/* map to display assets' files */}
                {podcast.node.fichier &&
                  podcast.node.fichier.map((fichier, index) => (
                    <audio
                      key={index}
                      ref={audioPlayer.current[index]}
                      src={fichier.url}
                      preload="metadata"
                      onLoadedData={() => onLoadedMetadata(index)}
                    />
                  ))}

                {/* desktop btn */}
                <div className="audioPlayer__player-btn displayNoneMobile">
                  <button type="button" onClick={() => backThirty(index)} className="audioPlayer__btn">
                    <TbPlayerTrackPrevFilled />{' '}
                  </button>
                  <button
                    type="button"
                    onClick={() => togglePlayPause(index)}
                    className="audioPlayer__main-btn"
                  >
                    {isPlaying ? <TbPlayerPauseFilled /> : <TbPlayerPlayFilled />}
                  </button>
                  <button type="button" onClick={() => forwardThirty(index)} className="audioPlayer__btn">
                    <TbPlayerTrackNextFilled />{' '}
                  </button>
                </div>

                <div className="audioPlayer__player-bar">
                  {/* current time */}
                  <div className="audioPlayer__currentTime">{calculateTime(currentTime)}</div>
                  {/* Barre de progression */}
                  <div>
                    <input
                      type="range"
                      className="audioPlayer__progressBar"
                      defaultValue="0"
                      ref={progressBar.current[index]}
                      onChange={() => changeRange(index)}
                    />
                  </div>
                  {/* duration */}
                  <div className="audioPlayer__duration">
                    {(duration && !Number.isNaN(duration)) && calculateTime(duration)}
                  </div>
                </div>

                {/* mobile btn */}
                <div className="audioPlayer__player-btn displayNoneDesktop">
                  <button type="button" onClick={() => backThirty(index)} className="audioPlayer__btn">
                    <TbPlayerTrackPrevFilled />{' '}
                  </button>
                  <button
                    type="button"
                    onClick={() => togglePlayPause(index)}
                    className="audioPlayer__main-btn"
                  >
                    {isPlaying ? <TbPlayerPauseFilled /> : <TbPlayerPlayFilled />}
                  </button>
                  <button type="button" onClick={() => forwardThirty(index)} className="audioPlayer__btn">
                    <TbPlayerTrackNextFilled />{' '}
                  </button>
                </div>
              </div>
            </article>
          </div>
        </section>
      ))}
    </Container>
  );
}

Check if an element is visible if it is hide it

So I am trying to show a search box when you click the search icon in WordPress. The issue I am having is i want it to hide if you click anyplace else on the site.

Currently this is the code I am using and it works if you click the icon on and off but i want lost focus click also.
<script> function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } </script>
The other script i was trying to use is this but it doesnt seem to have any effect.

`
<script>
document.addEventListener('click', function handleClickOutsideBox(event) {
 const box = document.getElementById('myDIV');

if (window.getComputedStyle(x).visibility === "visible") {
x.style.visibility = "hidden";
}
});
</script>

`
Any help would be great thank you.

The second art of my code

 ```
 <script>
 document.addEventListener('click', function handleClickOutsideBox(event) {
  const box = document.getElementById('myDIV');

 if (window.getComputedStyle(x).visibility === "visible") {
 x.style.visibility = "hidden";
 }
 });
 </script>
 ```

I thought would hide it if it saw it was visible but it isnt working.

Why do I keep getting the error message “ER_DATA_TOO_LONG” in Sequelize even though I adjusted the data type in the model?

I’m using Sequelize with MySQL to create a table in my schema. I’ve created models for my tables but I’m having trouble with one in particular. Here’s the code snippet for it:

const Author = require('./author');
const Genre = require('./genre'); 

const Book = sequelize.define('Book', {
  title: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  summary: {
    type: DataTypes.TEXT,
    allowNull: false,
  },
  isbn: {
    type: DataTypes.STRING,
    allowNull: false,
  },
});

Book.belongsTo(Author, { as: 'author' });
Book.hasMany(Genre, { as: 'genres' });

I’m also using a Node.js file to actually create the tables and insert data into them. Here’s a function from the file that creates a book based on the Book model and inserts it into the book table:

async function bookCreate(index, title, summary, isbn, author, genre) {
  const bookdetail = {
    title: title,
    summary: summary,
    author: author,
    isbn: isbn,
  };
  if (genre != false) bookdetail.genre = genre;

  const book = await Book.create(bookdetail);
  await book.save();
  books[index] = book;
  console.log(`Added book: ${title}`);
}

// Function being called
bookCreate(0,
      "The Name of the Wind (The Kingkiller Chronicle, #1)",
      "I have stolen princesses back from sleeping barrow kings. I burned down the town of Trebon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age than most people are allowed in. I tread paths by moonlight that others fear to speak of during day. I have talked to Gods, loved women, and written songs that make the minstrels weep.",
      "9781473211896",
      authors[0],
      [genres[0]]
    )

When I tried running my Node.js file using the node command, I got this error in the terminal saying the data for the summary was too long:

code: 'ER_DATA_TOO_LONG',
    errno: 1406,
    sqlState: '22001',
    sqlMessage: "Data too long for column 'summary' at row 1",
    sql: 'INSERT INTO `Books` (`id`,`title`,`summary`,`isbn`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);',
    parameters: [
      'The Name of the Wind (The Kingkiller Chronicle, #1)',
      'I have stolen princesses back from sleeping barrow kings. I burned down the town of Trebon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age than most people are allowed in. I tread paths by moonlight that others fear to speak of during day. I have talked to Gods, loved women, and written songs that make the minstrels weep.',
      '9781473211896',
      '2023-11-28 16:14:10',
      '2023-11-28 16:14:10'
    ]

I’m not sure why I’m getting that error since I have the data type for the summary property of the Book model set to TEXT instead of STRING, which I believe is supposed to disable length checking but I could be wrong. Can anyone help me?

register is not defined

im getting this error when i run my code
VM120 signup.html:1 Uncaught ReferenceError: register is not defined
at HTMLInputElement.onclick (VM120 signup.html:1:1)

im making a code that detects when i press the submit btn
html:

html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> signing up </title> 
    <link rel="stylesheet" href="../layout/styles/signupstyle.css">
   </head>
<body>
  <div class="wrapper">
    <h2>sign up</h2>
    <form action="#">
        <div class="input-box">
            <input type="text" placeholder="Enter your first name" id="firstname" required>
          </div>
        <div class="input-box">
            <input type="text" placeholder="Enter your last name" id="lastname" required>
        </div>
        <div class="input-box">
            <input type="text" placeholder="Enter your birthdate" id="birthdate" required>
        </div>
      <div class="input-box">
        <input type="text" placeholder="Enter your email" id="email" required>
      </div>
      <div class="input-box">
        <input type="password" placeholder="Create password" id="password" required>
      </div>
      <div class="input-box">
        <input type="password" placeholder="Confirm password" id="confirmpassword" required>
      </div>
      <div class="input-box button">
        <input type="Submit" value="Register Now" onclick="register()">
      </div>
      <div class="text">
        <h3>Already have an account? <a href="login.html">Login now</a></h3>
      </div>
    </form>
  </div>
</body>
<script src="../layout/scripts/signup.js"></script>
</html>

javascript:
function register(){
    let 1stname=document.getElementById("firstname")
    console.log("hi "+1stname)
}

i searched every where but i couldn’t find a problem

How To Display Certain Text In A Shared Div According To The Different Pages The Javascript Is On?

I am new here. And I am working on a webcomic layout script. I want to show the page’s info (Chapter #, Page #, Chapter Title, etc.) on the designated pages. An example is–

If the visitor is on page two of the comic I want it to say something like this:

Chapter #01: The Start-Up | Page #02 – Comic #002 (Nov.28.2023)

<div id="comicInfo">
<div id="ch"></div>
<div id="pg"></div>
<div id="comno"></div>
</div>

Maybe the code will be something like:

if (document.URL.includes("comics/page001.htm") ) {
document.getElementById("ch").innerHTML = "Chapter #01: The Start-Up";
document.getElementById("pg").innerHTML = "Page #01";
document.getElementById("comno").innerHTML = "Comic #001";

} else if (document.URL.includes("comics/page002.htm") ) {
document.getElementById("ch").innerHTML = "Chapter #01: The Start-Up";
document.getElementById("pg").innerHTML = "Page #02";
document.getElementById("comno").innerHTML = "Comic #002";

} else if (document.URL.includes("comics/page003.htm") ) {
document.getElementById("ch").innerHTML = "Chapter #01: The Start-Up";
document.getElementById("pg").innerHTML = "Page #03";
document.getElementById("comno").innerHTML = "Comic #003";
}

else (document.URL.includes("comics/page004.htm") ) {
document.getElementById("ch").innerHTML = "Chapter #01: The Start-Up";
document.getElementById("pg").innerHTML = "Page #04";
document.getElementById("comno").innerHTML = "Comic #004";
}

I would appreciate the help.

I tried the above code and couldn’t get it to work at all.

Use variable on left size of variable declaration without Eval()

I want to do something like this but without exec():

let variablename = "myVar"

exec(`let ${variablename} = 'foo'`)

console.log(myVar)
//output: "foo"

Unfortunately in Javscript I cannot include variables on the left side of definitions

This won’t work:

let variablename = "myVar"

let `${variablename}` = 'foo'

console.log(myVar)
//output: "foo"

I know I could use an object but I wanted to ask if there’s a more direct way that would allow myVar to be defined as a global variable.

I’m using this in a google chrome and firefox extention, so I need this to be compatable with google chrome Manifest v3 for extentions

Thank you to all answers!