Vue Router Navigation Issue: Can’t navigate back using browser’s back button

I’m working on a Vue.js (v. 2.6) application that uses Vue Router for navigation between different pages. After logging in, the user is redirected to the home page with the following code:

this.$router.push(‘/app’);

The issue is that after navigating to other pages within the app (by clicking buttons that load other routes), the user is unable to use the browser’s back button to return to the previous page or the home page. Route changes but the view doesn’t. It seems like the browser history isn’t being handled correctly. In my browser first I typed https://example.com, and everything works fine but example.com/random_string doesn’t. I’m working with hash mode

What I’ve tried:

  • I’ve confirmed that this.$router.push correctly adds a new entry to the browser’s history.

  • I used this.$router.replace in some cases to avoid adding multiple entries to the history, but the behavior remains the same.

  • I have 0 errors in the console

Problem:
When I navigate between different pages in the app (e.g., /app/dashboard, /app/events), the routing works fine. However, if I try to use the browser’s back button to go back to the previous page, the navigation doesn’t work as expected, and the app doesn’t go back to the home page or the previously visited route.

  • My main.js is configured as follows:
const router = new VueRouter({
    mode: 'hash',
    base: ROUTERPATH,
    routes: [{
            path: '/',
            name: 'Login',
            component: Login
        },
        {
            path: '/loginusers',
            name: 'LoginUsers',
            component: LoginUsers
        },
        {
            path: '/user',
            name: 'User',
            component: MenuUser, 
            children: [{
                    path: '/',
                    name: 'DashBoardUser',
                    component: DashBoardUser
                },
                {
                    path: ':section(dashboard|events)',
                    name: 'DashBoardUserSection',
                    component: DashBoardUser,
                    props: true
                },
            ]
        },
        {
            path: '/app',
            name: 'App',
            component: Menu,
            children: [{
                    path: '/',
                    name: 'Dashboard',
                    component: Dashboard
                },
                {
                    path: 'logout',
                    name: 'Logout',
                    component: Logout
                },
            ]
        },
    ]
    })
router.beforeEach((to, from, next) => {
    if (to.path !== '/' &&
        !to.path.startsWith('/loginusers')
    ) {

        var isUser = false;
        if (to.path.startsWith('/ute/') || to.path == '/ute') {
            isUser = true;
        }

        if ((localStorage.getItem('token') || '') === '') {
            (isUser ? router.push('/loginusers') : router.push('/'))
            //router.push('/')
        } else {

            var token = localStorage.getItem('token')
            axios.get(NAMESPACE + 'rest/logged', {
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    }
                })
                .then(response => {
                    // JSON responses are automatically parsed.
                    try {
                        if (!response.data.error) {
                            if (response.data.token != null) {
                                localStorage.setItem('token', response.data.token)
                                next()
                            } else {
                                (isUser ? router.push('/loginusers') : router.push('/'))
                            }
                        } else {
                            // not logged
                            (isUser ? router.push('/loginusers') : router.push('/'))
                        }
                    } catch (e) {
                        (isUser ? router.push('/loginusers') : router.push('/'))
                    }
                })
                .catch(e => {
                    (isUser ? router.push('/loginusers') : router.push('/'))
                    e
                })
        }
    } else {
        next()
    }
})

–> So, you go to example.com, you login, homepage, it works. You go to https://example.com/random_string, you login, homepage, click on a button, other page, route change, view change, you want to go back with arrows, you cannot (only route change)

I’m looking for a solution that ensures proper browser history handling using hash mode.

Thanks in advance for any help!`

Is there a short syntax in javascript for a call chain containing synchronous and asynchronous methods of the same class?

I know of 2 ways that are not very convenient and look inelegant:

  1. Via then:

    (new TestClass).syncMethod().asyncMethod().then(self => self.anotherSyncMethod())

  2. Via await:

    (await (new TestClass).syncMethod().asyncMethod()).anotherSyncMethod()

I expect it to be something like this (pseudocode):
(new TestClass).syncMethod().asyncMethod()->anotherSyncMethod()
where -> is the transition from an async method to a synchronous one.

Is there something like this in JS, and if not, is there any plans for it in the future?

websocket not able to connect with no error reason [closed]

I have a web application which opens websocket to get some data, today (with no changes on server side) strange thing start happening. At application start (angular web page) websocket (rxjs) is not able to connect, and has no error message:
error message

And it’s more strange that after some time (usually 10-20 minutes) application finally able to connect to the web socket (it has reconnect logic in case if no data has been got):
retries

Any advises how to debug such situation?

I have a server on one of public cloud platfor (nginx as server with static pages + springboot), I did fresh deployment in different region and behavior is same no maters how many users are connected. I tried oldest images to be sure that nothing has changed in the code, but same result

Also no errors on springboot side

Combining multiple datasets in chartjs

Currently I have 2 points in my line chart’s dataset as seen in the screenshot.
Now I want to add 4th dataset like in the screenshot, its the non-linear dataset.

But 4th non-linear dataset is a calculated dataset and it has around ~200-400 points.

But the thing is, first datasets (2 point datasets) are get cut-off because I have only 2 points.
What I would like to achieve is, I want to spread 2 points dataset across the chart and have 2 ticks on x-axis which is first and end date.

here is example; https://stackblitz.com/edit/vitejs-vite-utbcv1?file=src%2FLineChart.tsx

this is currently an example;
enter image description here

and this is what I want to achieve (non-linear is the big dataset)
enter image description here

Saving multiple IDs into globals

The response of the API I’m testing returns an array with multiple objects and I want to save one of those value into a global variable, I know how to do this for a single entry using:

const jsonData = JSON.parse(responseBody);
pm.globals.set("my_id", jsonData.id);

but how can I do this for multiple IDs into one response? This API will always return two objects so two IDs, something like:

{
    "value": [
        {
            "id": "FIRST_RANDOM_UUID",
        },
                {
            "id": "SECOND_RANDOM_UUID",
        },    ]
}

If possible I want to name these ID1 and ID2.

Am i be able to get a job after learning javascript, react.js and react native in field of app development? [closed]

I am currently learning JavaScript and have set a plan to further my skills by learning React.js and then React Native. Given that I am new to these technologies and have only a bit of prior knowledge in web development, I am wondering if this sequence of learning is a solid approach for securing a job in the mobile development field. JavaScript, as a foundational language, seems essential, and moving on to React.js will help me understand the principles of building interactive web applications. Following this, learning React Native should enable me to apply those web development skills to create mobile applications. Since React Native leverages the knowledge gained from React.js, it seems like a logical next step for transitioning from web to mobile development. My goal is to ensure that this learning path will make me competitive and well-prepared for job opportunities in mobile development. Is this plan effective in positioning myself for a career in this field, and are there any additional steps or skills I should consider to enhance my employability in the mobile development industry?

D3 Graph should extend when currentStepIndex is triggerd and not rerendered

im trying to get in touch with the D3 library in my React project and so far so good. But i have one problem: i want to animate a graph/line step by step as defined in the filteredData depending on the CurrentStepIndex, which is triggerd by the Scrollama Library with .

useEffect(() => {
    const svg = d3.select(svgRef.current).select("svg").remove();


    const observer = new IntersectionObserver((entries) => {
      const entry = entries[0];
      setMyGraphIsVisible(entry.isIntersecting);
      console.log(myGraphIsVisible);
    });

    observer.observe(svgRef.current);

    const svgContainer = d3
      .select(svgRef.current)
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", `translate(${margin.left},${margin.top})`); //svg sits nice and coozy in the container

    const tooltip = svgContainer
      .append("foreignObject")
      .attr("class", "tooltip")
      .style("display", "none") // Tooltip zunächst ausblenden
      .attr("width", 80) // Breite des Tooltip-Bereichs
      .attr("height", 60); // Höhe des Tooltip-Bereichs

    const tooltipContent = tooltip
      .append("xhtml:div")
      .attr("class", "tooltip-content") // Klasse für Styling-Zwecke
      .style("background-color", "steelblue")
      .style("color", "white")
      .style("border-radius", "5px")
      .style("font-size", "12px");

    
    const x = d3
      .scaleLinear()
      .domain([0, d3.max(data2, (d) => d.year)])
      .range([0, width]);

    const y = d3.scaleLinear().domain([0, 100]).range([height, 0]);

    
    svgContainer
      .append("g")
      .attr("transform", `translate(0,${height})`)
      .call(d3.axisBottom(x).ticks(9).tickFormat(d3.format("d")));

    
    svgContainer.append("g").call(d3.axisLeft(y)).attr("class", "y-axis");

    
    svgContainer
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 0 - margin.left)
      .attr("x", 0 - height / 2)
      .attr("dy", "1em")
      .style("text-anchor", "middle")
      .style("font-size", "14px")
      .style("fill", "#777")
      .style("font-family", "sans-serif")
      .text("Erwerbsquote in %");

    

    svgContainer
      .append("text")
      .attr("class", "source-credit")
      .attr("x", width - 300)
      .attr("y", height + margin.bottom)
      .style("font-size", "9px")
      .style("font-family", "sans-serif")
      .style("fill", "#777")
      .text("Quelle: https://doku.iab.de/kurzber/2024/kb2024-10.pdf");

   
    svgContainer
      .selectAll("xGrid")
      .data(x.ticks().slice(1))
      .join("line")
      .attr("x1", (d) => x(d))
      .attr("x2", (d) => x(d))
      .attr("y1", 0)
      .attr("y2", height)
      .attr("stroke", "#e0e0e0")
      .attr("stroke-width", 0.1);

    // Add horizontal gridlines
    svgContainer
      .selectAll("yGrid")
      .data(y.ticks().slice(1))
      .join("line")
      .attr("x1", 0)
      .attr("x2", width)
      .attr("y1", (d) => y(d))
      .attr("y2", (d) => y(d))
      .attr("stroke", "#e0e0e0")
      .attr("stroke-width", 0.1);

   
    const line = d3
      .line()
      .x((d) => x(d.year))
      .y((d) => y(d.number));

   

    const filteredData =
      currentStepIndex === 1
        ? data2.slice(0, 4)
        : currentStepIndex === 2
        ? data2.slice(0, 7)
        : currentStepIndex === 3
        ? data2.slice(0, 9)
        : data2.slice(0, 0);

    const path = svgContainer
      .append("path")
      .datum(filteredData)
      .attr("fill", "none")
      .attr("stroke", "yellow")
      .attr("stroke-width", 1.5)
      .attr("d", line);

    
    const totalLength = path.node().getTotalLength();
    path
      .attr("stroke-dasharray", totalLength)
      .attr("stroke-dashoffset", totalLength)
      .transition()
      .duration(2000)
      .attr("stroke-dashoffset", 0);

    svg.selectAll("rect").remove(); // Remove any existing rectangles
    if (currentStepIndex === 4) {
      svgContainer
        .append("path")
        .datum(data2)
        .attr("fill", "none")
        .attr("stroke", "yellow")
        .attr("stroke-width", 1.5)
        .attr("d", line);

      const path2 = svgContainer
        .append("path")
        .datum(data3)
        .attr("fill", "none")
        .attr("stroke", "white")
        .attr("stroke-width", 1.5)
        .attr("d", line);

      const totalLength2 = path2.node().getTotalLength();

      path2
        .attr("stroke-dasharray", totalLength2)
        .attr("stroke-dashoffset", totalLength2)
        .transition()
        .duration(2000)
        .attr("stroke-dashoffset", 0);
    }
    });

  }, [myGraphIsVisible, currentStepIndex]);

Data:

  const data2 = [
    { year: 0, number: 0 },
    { year: 1, number: 9 },
    { year: 2, number: 26 },
    { year: 3, number: 44 },
    { year: 4, number: 51 },
    { year: 5, number: 60 },
    { year: 6, number: 70 },
    { year: 7, number: 75 },
    { year: 8, number: 86 },
  ];

  const data3 = [
    { year: 0, number: 77.6 },
    { year: 1, number: 77.7 },
    { year: 2, number: 77.8 },
    { year: 3, number: 77.7 },
    { year: 4, number: 78.0 },
    { year: 5, number: 78.9 },
    { year: 6, number: 79.6 },
    { year: 7, number: 80.5 },
    { year: 8, number: 79.0 },
  ];

I know its saying in the first line
const svg = d3.select(svgRef.current).select("svg").remove();
which cause the issue, but if i get rid of this line it will render each Step a new SVG.

I tried different things, like an if clause where im asking if there is an existing SVG, but then my SVG is not working properly, like “Uncaught TypeError: Cannot read properties of undefined (reading ’empty’)”

Any suggestion to solve this Problem?

Thanks in Advance!

Isolate container div from website’s styles without iframe

I have a simple textarea and a preview modal which shows me how the content of the textarea looks like in an email (so basically loads and shows the content as HTML).

Now, this preview is affected by my website’s styles and I want to isolate it, so that it’s as plain and exact as it would show when sent as email. I don’t want to use iframe as it’s not responsive, are there better ways to do it?

I’m using VueJS, but ideally I would like a solution that doesn’t require installing a plugin just for this. The solution I’m looking for is either in CSS, or vanilla javascript, or built-in Vue functionality

Create embroidery images from png or text [closed]

I am creating a canvas in javascript. I am loading an image to the canvas and displaying an image on the canvas, I want this image to be converted to an embroidery filter view.

I can use python nodejs php as a backend. How can I do this, is there a library or function to do this?

I have been searching for 4 days and I can’t find anything

I want a library that I can use to convert images or text to an embroidery filter view.

How to make node.js ignore css files

I can’t run the tests with Mocha in my vanilla javascript project when I have a CSS file import because I can’t get Node to ignore that specific extension.

I get this error:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.css”
at new NodeError (node:internal/errors:405:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
at defaultGetFormat (node:internal/modules/esm/get_format:124:36)
at defaultLoad (node:internal/modules/esm/load:84:20)
at nextLoad (node:internal/modules/esm/loader:163:28)
at ESMLoader.load (node:internal/modules/esm/loader:603:26)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
at new ModuleJob (node:internal/modules/esm/module_job:64:26)
at #createModuleJob (node:internal/modules/esm/loader:480:17)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)
at async ModuleWrap. (node:internal/modules/esm/module_job:79:21)

Here is a sample repository to replicate the issue, hoping it will be helpful:

https://github.com/Marco0491/mocha-issue-simulation

Everything I’ve found so far is outdated and doesn’t work in my case.

Navigation in external URLs within TMA (Telegram Mini App)

Inside of my Telegram Mini App, say I have an anchor tag <a href="google.com">External URL</a>, which then opens inside of the telegram app itself. As is, there is no way to navigate back to the original app, except clicking the ‘Close’ button in the top left and then opening the TMA again from the bot main button.

I can enable the ‘Back’ button with window.Telegram.WebApp.BackButton.show();, which visually changes the ‘Close’ button to a ‘< Back’ button but which does nothing on click. I’ve tried to bind it to navigate back like so:

window.Telegram.WebApp.BackButton.onClick(() => {
  alert("Navigated back!");
  history.back();
});

While the alert fires when inside the original app, once the user clicks into the external link, the back button no longer works (and the alert no longer fires). As such I can guess that the function is only bound to the button when in the original app, which is not helpful to me as I’m trying to allow the user to navigate back to the app after viewing an external file. How can I permanently bind the function to the back button or, failing that, achieve some way to allow the users to navigate back to the original app after viewing an external file?

How to detect right click while mouse is moving?

Is there a way to detect a right click when moving the mouse?

It is easy to detect left click when moving mouse but I can’t detect right click

document.addEventListener('mousemove', e => console.log(e.buttons || e.button))

And also window.oncontextmenu does not fires when mouse is moving

Prevent validateOnChange using custom fields in VeeValidate

In my VueJs app, I’ve got the following custom field component in VeeValidate:

<template>
  <input v-model="value" type="text" />
</template>

<script setup>
  import { useField } from 'vee-validate'

  const props = defineProps({
    name: {
      type: String,
      required: true
    }
  })

  const { value } = useField(props.name)
</script>

My form is set with the following configurations:

  configure({
    validateOnBlur: false,
    validateOnChange: false
  })

But my custom field component is still validating on Change and on Blur. How can I make the custom field work like any other field and respect my form configurations?

CSRF token for AJAX call in attached javascript file

I’m working in Codeigniter 4 with CSRF protection enabled. I have an AJAX call in an attached js file, and I can’t figure out how to generate the CSRF token. Previously, I have done it in php files with embedded js, but in the attached js file I can’t run php.

In the attached js file I have:

//makes a tooltip with description of analysis (header)
    $('.tbl-header').each(function () {
        makeHeaderInfo($(this))
    })

function makeHeaderInfo(header) {
        var analysis = header.hasClass('seed') ? 'Seedling ' + header.text().toLowerCase() : 'Sapling ' + header.text().toLowerCase();
        var posturl = baseURL + "forest_regen/getAnalysisDetails";
        var data = {};
        data['analysis'] = analysis;
//This is what I would do in a php file...
//       var csrfName = '<?= csrf_token() ?>'; 
//       var csrfHash = '<?= csrf_hash() ?>';   
//       data[csrfName]=csrfHash;
        $.when($.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})).done(function (result) {
            var description = (result.fldDescription == null) ? 'No description for this analysis yet' : result.fldDescription
            header.children('.header-info').attr('title', description)
                    .tooltip({
                        trigger: 'click hover',
                        placement: 'top',
                        container: 'body'
                    })
        })
    }
    ;

I tried defining the variables in the php file which has this js file attached, but I get “csrfName is not defined.” I’m not sure how to pass the variables to the js file?

Is there a way to generate the csrfName and csrfHash in javascript or jquery? Or another way to accomplish this?

Thank you!

InvalidKeyMapError in Google Javascript API

I have been facing this error in my React project whenever I use Maps JavaScript API along with Google places API.
Maps JavaScript API error: InvalidKeyMapError

Here’s the code:

return (
    <SectionWrapper id={'generate'} header={"Generate your Dream Trip"} title={["Tell us your", "Travel","Preferences"]}>
      <Header index={'01'} title={'Pick a destination'} />
      <GooglePlacesAutocomplete className='bg-slate-950 border border-solid border-orange-400'>
        apiKey={import.meta.env.VITE_GOOGLE_PLACE_API_KEY}
      </GooglePlacesAutocomplete>

And I have added the script tag to my index.html file:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/logowanderly.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Wanderly</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://maps.googleapis.com/maps/api/js?key=VITE_GOOGLE_PLACE_API_KEY&libraries=places"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

Need help with this ASAP(PS: the value that I have entered for my key is absolutely correct).

I tried checking my key and making a new key but nothing is helping.