Naivgate tabs by url HTML

Let’s say I have this ul which filters a grid of items based on data-filter:

<ul>
    <li><a href="#" data-filter="l1">Link1</a></li>
    <li><a href="#" data-filter="l2">Link2</a></li>
    <li><a href="#" data-filter="l3">Link3</a></li>
    <li><a href="#" data-filter="l4">Link4</a></li>
</ul>

When entering the url like this: www.something.com/#l1, I want to simulate a click on Link1. And when manually clicking on Link1, I want to add to the url /#l1.

I can use jQuery to add a $(document).ready() function, to get the querystring from the URL and clicking with .click(). But I have no idea how to change the url when clicking on a <a>.

Is there a simpler way of doing this?

REACT JS – Eventualy my addeventlistener works, eventually not

What’s going on in my code? Basically, I’m trying to use try/catch on my submit button, but there’s no response, unless I “randomly” change the code and ctrl+z, which is weird. Can you guys help me?

function Search() {
    const apiKey = '34a37e23f7b13413d266dd15e21f63f8'
    const apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=metric&q="
   
    const searchBox = document.querySelector('.search input')
    const searchBtn = document.querySelector('.search button')
    const weatherIcon = document.querySelector(".weather-icon")  
    
  
        
    async function checkWeather(cidade) {
        const response = await fetch(apiUrl + encodeURIComponent(cidade) + "&appid=" + apiKey)
        const data = await response.json()
        
        document.querySelector('.cidade').innerHTML = data.name
        document.querySelector('.temperatura').innerHTML = Math.round(data.main.temp) + "  °C"
        document.querySelector('.umidade').innerHTML = data.main.humidity + "%"
        document.querySelector('.vento').innerHTML = Math.round(data.wind.speed) + "km/h"
        console.log(data)

        if (data.weather[0].main == 'Clouds') {
            weatherIcon.src = cloud
        } else if (data.weather[0].main == 'Clear') {
            weatherIcon.src = sun
        } else if (data.weather[0].main == 'Rain') {
            weatherIcon.src = rain
        } else if (data.weather[0].main == 'Drizzle') {
            weatherIcon.src = drizzle
        }
        document.querySelector('.weather').style.display = "block"
    }
        
try{
    searchBtn.addEventListener("click", ()=>{
        checkWeather(searchBox.value)
        console.log('funfou')})    
} catch(e) {

}
}
export default Search

I tried changing it to outside try catch block, but react said it couldnt work

React Native BottomSheet Many Modals in Context Provider

I’ve created a Context for “Sheets” and I’m trying to map through an array of Modal components to display them when a function is run inside of a component. For the sake of shortening the code snippet here, I’ve removed my imported Modals and replaced it with a simple text component.

Error: right operand of ‘in’ is not an object

SheetContextProvider

import { createContext, useContext, useRef } from 'react';
import { Text } from 'react-native';
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';

export const SheetContext = createContext({});
export const useSheetContext = () => useContext(SheetContext);

import Sheet from '../components/Sheet';

const sheets = [WalletSheet, ShippingSheet];

export default function SheetContextProvider({ children }) {
    const refs = useRef([]);

    function handleShowModal(index) {
        refs.current[index].present();
    }

    const value = { handleShowModal };

    return (
        <BottomSheetModalProvider>
            <SheetContext.Provider value={value}>
                {children}
                {sheets.map((item, index) => {
                    return (
                        <Sheet ref={(element) => (refs.current[index] = element)} key={index}>
                            <Text>Test</Text>
                        </Sheet>
                    );
                })}
            </SheetContext.Provider>
        </BottomSheetModalProvider>
    );
}

Sheet Component (Wrapping the BottomSheet component)

import { forwardRef } from 'react';
import { StyleSheet } from 'react-native';
import { BottomSheetModal } from '@gorhom/bottom-sheet';

const Sheet = forwardRef(function Sheet({ children }, ref) {
    const modalSnapPoints = '45%';

    return (
        <BottomSheetModal
            ref={ref}
            index={0}
            snapPoints={modalSnapPoints}
        >
            {children}
        </BottomSheetModal>
    );
});

export default Sheet;

Component where I’m calling the handleShowModal function

// Sheet index is referenced from sheets array in SheetContextProvider
const SHEET_INDEX = 1;
const LISTINGS_TEXT = 'Listings';

export default function Actions() {
    const { handleShowModal } = useSheetContext();

    return (
        <Pressable onPress={() => handleShowModal(SHEET_INDEX)} style={styles.action}>
            <MaterialIcons name="storefront" size={22} color="white" style={styles.icon} />
            <Text style={styles.text}>{LISTINGS_TEXT}</Text>
        </Pressable>
    );
}

React Interweave Library causing hydration error on runtime

I am creating a react component where I am fetching some data from the array of strings where there is some html code. I am using interweave library when looping through that array to render my table. The problem is the it renders correctly but I am getting hydration error on runtime. How to fix it?

export const RewardsFromInvestments = [
  
  "The Net  Yield Farming  Rewards directly attributable to the Token Holder shall be calculated and distributed to the Token Holder’s Account in Periodic Distributions using the following formula:",
  `For the purposes of clarity, the Yield Farming Rewards will comprise of profit generated from trading fees income and native token rewards income. The distribution of the Yield Farming Rewards are as follows:
  <table>
    <tr>
      <td>Trading Fee Income Allocated to Token Holders</td>
      <td>100%</td>
    </tr>
    <tr>
      <td>Trading Fee Income Allocated to ZaynFi</td>
      <td>0%</td>
    </tr>
    <tr>
      <td>Native Token Rewards Allocated to Token Holders</td>
      <td>80%</td>
    </tr>
     <tr>
      <td>Native Token Rewards Allocated to ZaynFi </td>
      <td>20%</td>
    </tr>
  </table>`,

The code for creating the list dynamically:

 <ol
 className={`list-[lower-roman] font-normal text-[16px]  pl-5 outside ${styles.listTerms}`}
   >
 {RewardsFromInvestments.map((i) => (
  <li className={styles.listContent}>{<Markup content={i} />}</li>
   ))}
 </ol>

Error during runtime
Web output for the table

This runtime error goes away whenever I comment this line. It makes it clear that this is causing the problem. Please help me fix it.

<li className={styles.listContent}>{<Markup content={i} />}</li>

Change svg image with css or javascript?

I’m trying to change an SVG icon created by CreatableSelect in React, but I’m trying to use only CSS to do this:

this is my html element created by the library

HTML element:

.css-1hb7zxy-IndicatorsContainer .css-tlfecz-indicatorContainer svg>path {
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-down' viewBox='0 0 16 16'><path fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/></svg>") no-repeat 0 0 !important;
  padding-left: 20px;
  color: #000;
}
<div class=" css-tlfecz-indicatorContainer" aria-hidden="true">
  <svg height="20" width="20" viewBox="0 0 20 20" aria-hidden="true" focusable="false" class="css-tj5bde-Svg">
  <path d="M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"></path>
  </svg>
</div>

also, tried with an url from font awesome free to test, but failed to.

thanks for everyone in advance to help me.

I want to change the “d” element inside the svg tag for this

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/> </svg>

Nodemailer form doesn’t work on the Firefox web browser

I was trying to implement a form that uses Next.js & Nodemailer to send emails, and it works just fine on Chrome & Bing. However, I am unable to send emails using Firefox.

This is the button that inputs the form data to the backend (in pages/index.js):

<input type="submit" onClick={onSubmit} disabled={!values.name || !values.subject || !values.email || !values.message} />

This is the function that is called onClick (in pages/index.js):

  const onSubmit = async () => {
    try {
      await sendContactForm(values);
    } catch (error) {
      console.log(error);
    }
  };

This is the function that awaits the form data (in lib/api.js):

export const sendContactForm = async (data) =>
  fetch("/api/contact", {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json", Accept: "application/json" },
  }).then((res) => {
    if (!res.ok) throw new Error("Failed to send message");
    return res.json();
  });

This is the function that sends the email (the nodemailer configuration was done in a different file) (in pages/api/contact.js):

import { mailOptions, transporter } from "config/nodemailer.js";

const handler = async (req, res) => {
  if (req.method === "POST") {
    const data = req.body;
    if (!data || !data.name || !data.email || !data.subject || !data.message) {
      return res.status(400).send({ message: "Bad request" });
    }
    try {
      await transporter.sendMail({
        ...mailOptions,
        ...generateEmailContent(data), //This is a function that returns the user inputted form data as a string
        subject: data.subject,
      });
      return res.status(200).json({ success: true });
    } catch (err) {
      console.log(err);
      return res.status(400).json({ message: err.message });
    }
  }
  return res.status(400).json({ message: "Bad request" });
};

Here is the GitHub repository as well for more context: https://github.com/Jacques-Bisset/nodemailer-testing

Here are some things I tried in the Firefox settings:

  • Disabled HTTPS-only mode
  • Turned browser security mode to “standard” instead of “strict”
  • Unmarked all checkboxes in the “Deceptive Content and Dangerous Software Protection” settings

None of these configurations seem to have done anything

As I said before, this code works perfectly fine in other web browsers – it is in Firefox specifically where no email is sent for whatever reason.

However, when I click the submit button on Firefox, this message pops up in the terminal:

warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

This also only occurs for Firefox and not other web browsers.

Thank you for any help in advance.

click video only if selector text is present – Puppeteer NodeJS

I have a code snippet that once goes to a youtube link, it gets videos to comment on by getting the links and then opening them in a new tab.
I’m trying to get it to be so that it only gets the video link and comments if this selector is present and has the text of it say a number less than 5. (uploaded [5 – 1 minute(s)/second(s)] ago), if there aren’t any videos that suitable, then the page will reload after 10seconds, and try again until 3 total videos have been found (over the time of running the script).

I tried using catching but it doesn’t work as I don’t exactly understand how to do this very well in my situation.

here is the selector of the time uploaded ago (as defined):

uploadedago : "#metadata-line > span:nth-child(4)",

(that’s in another file called “constants>selector>index.js”.)

here is the code that I’m working with:

// times the selector must say on the page
const uploadtimes = ("5 minutes", "4 minutes", "3 minutes", "2 minutes", "1 minute", "seconds", "seconds")

         try
         {
            if (tweet.includes("shorts"))
            {
               await pages.goto(tweet.replace(/shorts/, "watch"));
            }
            else
            {
               // console.log(tweet);
               await pages.goto(tweet);
            }
            try
            {
               await likeVideos.likeVideos(pages);
            }
            catch (error)
            {
               console.log(error);
            }
            await pages.bringToFront();
            await pages.waitForTimeout(4000);
            await pages.evaluate(() =>
            {
               window.scrollBy(0, 550);
            });

            try
            {
               await pages.waitForSelector(selector.catchErrorInComment,
               {
                  timeout: 4000
               });
               console.log("Can't Comment");

               await pages.close();
            }
            catch
            {
               await pages.waitForSelector(selector.inputComment,
               {
                  timeout: 4000,
               });

               await pages.evaluate(() =>
               {
                  document.querySelector('#simplebox-placeholder').click();
               });
               spinners.update('comment',
               {
                  text: 'collecting comments to copy .. ',
                  color: 'yellow',
               });

               if (config.copycomment && config.ai == false) 
               {
                  await copycommnet.copyComment(pages, spinners, config);
               }else if(config.ai){
                  await aiCommented.createComments(pages , spinners ,title, config)
               }
               else if(!config.copycomment && !config.ai)
               {
                  await manualComment.manualComment(pages, spinners, config);
               }else{
                  console.log(" Check Your Configuration")
               }
               await pages.waitForTimeout(config.delay * 1000);
               await pages.close();
               spinners.succeed('comment',
               {
                  text: 'Success commenting',
                  color: 'yellow',
               });
               Logger.log('./logs/succesCommenting.log', config.usernamegoogle, tweet, 'success')
            }
         }
         catch (e)
         {
            await pages.close();
      
               Logger.log('./logs/errorCommenting.log', config.usernamegoogle, tweet, 'failed', e)
          
         }
         await wait(config.delay);
      }

      spinners.add('delay',
      {
         text: `wait .. we are delaying for ${config.delaycomment}`,
         color: 'yellow',
      });
   }
   spinners.add('done',
   {
      text: `COMMENTS ADDED, FINISHING UP ..`,
      color: 'green',
   });
   await browser.close();
}

startApp(config, Config(paths,config,executablePath("chrome")));

function readLog()
{
   const data = fs.readFileSync('./logs/succesCommenting.log', 'utf8');
   return data;
}

Disclaimer: this is a script strictly used to scrape data on youtube only for my own channels. (it’s a link of keywords that only my videos are under in the tags section.)

vuejs class binding on dynamically loaded elements

I try to use vuejs on some elements. This is how I load the script in my jinja2 template:

{% block tail %}
  {{ super() }}
   <script src="/static/assets/js/vue.global.js"></script>
<script>
  const { createApp } = Vue

  createApp({
    data() {
      return {
        message: 'form-control shadow'
      }
    },
    delimiters: ['[[',']]']
  }).mount('#questions')
</script>
{% endblock %}

By clicking a button an html fragment as following is appended to a page element using jQuery.

<ul :class="message" class="" id="yesno">...</ul>

But the message isn’t bound to the element. However if I use this solution:

<ul  class="[[ message ]]"  id="yesno">...</ul>

The variable is set and it works. What could be the problem? Also, is my second solution an alternative for the first one?

RShiny DT last page navigation w/Javascript session$sendCustomMessage not executing with r function in action button

this is my 1st shiny app trying to incorporate Javascript so I know there are nuances Im probably missing here. I have an app where I’m trying to allow users to add rows and then the table goes to the last page where the row is added with an action button. Both actions work independently within separate observeEvents but when I try placing them in the same observeEvent block, the session$sendCustomMessage doesn’t go through. The row is added but the visual doesn’t go to the last page of the table. Code is below:

ui <- fluidPage(theme = shinytheme(“spacelab”),
navbarPage(
“App”,
tabPanel(“Search”,

                           mainPanel(
                             fluidRow(
                               column(3, selectInput("search_type_filter", label = "Type", choices =   c("All", "Derm", "Onc"), selected = "All")),
                               column(3, selectInput("search_active_filter", label = "Active", choices = c("All", "No", "Yes"), selected = "All"))
                             ),
                             DT::dataTableOutput("Table") 
                                                 tags$script(HTML("Shiny.addCustomMessageHandler('LastPage', function(message) {
                        var target = $('#Table .dataTable');
                        target.DataTable().page('last').draw(false);
                        });")),
                             actionButton("updateButton", "Update", class = "btn btn-primary"),
                             actionButton("addRowButton", "Add Hashtag"),
                             actionButton("resetButton", "Reset")
                             
                           )
                           
                           
                  )))
                  
  server <- function(input, output, session) {
    
    HTData <- reactiveValues(data = getDataFromLake(datalake_path, filename, endp))
    
    # Define reactive filtered data object
    fData <- reactive({
      data <- HTData$data
      if (input$search_type_filter != "All") {
        data <- data %>% filter(Type == input$search_type_filter)
      }
      if (input$search_active_filter != "All") {
        data <- data %>% filter(Active == input$search_active_filter)
      }
      return(data)
    })
    
    #Render Table
    output$Table <- DT::renderDataTable({
      datatable(
        fData(),
        editable = TRUE
        
      )
    }, server = TRUE)
    
    # Define function to add a new row to the data frame
    add_row <- function(data) {
      new_row <- c("", "", "", "") # Create a vector with empty values for each column
      names(new_row) <- names(data) # Set the column names of the new row to match the existing data frame
      rbind(data, new_row) # Concatenate the new row to the existing data frame and return the result
    }
    
    # Both in same block
    observeEvent(input$addRowButton, {
      HTData$data <- add_row(HTData$data) # Update the reactiveValues
      session$sendCustomMessage('LastPage', 'placeholder')
    })
    
    # Execute in separate blocks
    # observeEvent(input$addRowButton, {
    #   HTData$data <- add_row(HTData$data) # Update the reactiveValues
    # })
    # 
    # observeEvent(input$addRowButton, {
    #   HTData$data <- add_row(HTData$data) # Update the reactiveValues
    #   session$sendCustomMessage('LastPage', 'placeholder')
    # })

I’ve tried delaying the session$sendCustomMessage but I’m not getting the proper reaction using the shinyjs::delay() function which is another problem. I think delaying is the answer to get them to work in the same observeEvent block but couldn’t configure a proper solution. Foundation for session$sendCustomMessage comes from this page/solution, but my app is configured differently. R Shiny DT navigate to the table’s last page via an action button

Beginning with JavaScript (functions)

I am the entry level of learning JS and following a tutorial I am given this code

function shouldYouGoToTheLake(weather, waterTemperature) {
if (weather == "sunny") {
    return true;
} else if (waterTemperature >= 20) {
    return true;
} else {
    return false;
}
}

shouldYouGoToTheLake("sunny", 0); // true
shouldYouGoToTheLake("sunny", 10); // true
shouldYouGoToTheLake("cloudy", 25); // true
shouldYouGoToTheLake("cloudy", 18); // false

My question is how do you get a return? It is not enough to write shouldYouGoToTheLake(“sunny”, 0); as visual code studio runs the code without a return. Something is missing.

I did not run try to run all 4 returns in one sequence.

I run only 1 sequence

shouldYouGoToTheLake(“sunny”, 0);

Why does my code lint the one of identical code lines:

enter image description hereThe code on line 6 is identical to line 5. But the same code on line 6 doesnt cause any lint errors. Details of the errors have been highlighted in the image attached.

I was expect the first line be syntactically correct and not have any lint errors. But pasting the same code from an external source to vscode on the second line didnt cause any lint errors. But both code do the same thing and are exact. So why does line 5 show lint errors and why does the same code on line 6 pass without any lint errors.

I don’t get why JavaScript is single threaded in practice

Doing a quick google search you’ll find that JavaScript is single threaded this means that there is only one process that executes the code sequentially by putting instructions in a single call stack.

Now, in practice this is not the case. With runtime environments like Chrome (which uses the V8 engine) and Node.js (which also uses the V8 engine) it’s possible to have asynchronous code. The execution of that code is offloaded to a separate thread created by that runtime environment (or V8?) rather than trying to use the single thread.

Now the issue is that I’m confused as to what constitutes “JavaScript”. If all JavaScript engine like V8, Gecko, etc… are able to create new threads should we consider JavaScript not single threaded anymore? Or when we say “JavaScript” we refer to the spec that defines the language and not how people decide to implement it?

Another confusion is the difference between the V8 engine and the runtime environment. Is the asynchronous code handled by the V8 engine or the browser itself? Who creates the new thread?

If you tell me who provides the fs API in Node.js it’s clear that this is provided by the runtime environment Node.js and not the JavaScript engine.

Canvas drawing in a sandboxed iframe

I’m trying to draw into a canvas that is located in a sandboxed iframe. For some reason, this only works if allow-scripts is added to the sandbox white-list. I’ve tried finding any documentation on this limitation but couldn’t. What’s the reason? Is there a way to circumvent this? I cannot leave allow-scripts enabled because there the rest of the iframe content is based on untrusted input.

Canvas draw commands do seem pretty safe on the first glance but I must be missing some potential vector of attack so that browser vendors have decided to not allow doing so…

You can reproduce by accessing index.html on a server (e.g. python3 -m http.server). Opening index.html directly in the browser (as a file) won’t work because of an invalid origin in that case.

Any pointers or even better, solutions, are greatly appreciated.

index.html

<html lang="en">

<head>
    <script>
        function updateCanvas() {
            const ctx = document.querySelector('iframe').contentDocument.querySelector('canvas').getContext('2d')
            ctx.fillRect(25, 25, 100, 100);
        }
    </script>
</head>

<body>
    <iframe sandbox="allow-same-origin allow-scripts" src="./iframe.html"></iframe>

    <button onclick="updateCanvas()">Draw</button>
</body>

</html>

iframe.html

<html lang="en">
<body><canvas></canvas></body>
</html>