Is It Possible to Override Behavior of ons-button-back But Keep Default Animation?

I’m working on a small single page application in Onsen UI. It presents multiple screens that collect form data, all of which gets submitted to a mySql database on the backend on the last page template. As users are free to move back and forth through previously loaded templates, I’ve overridden the behavior of the Onsen back button to bring a previously visited page to the top of the navigation stack, rather than pop it off the stack. This is working, but I’d like to maintain the default animation of the back button. What is currently happening is I’m getting the same animation effect that occurs by default when a regular Onsen button is clicked. Is it possible to maintain the default back button animation behavior (e.g., slide out vs. slide in)?

If not, I’m wondering if it would be possible to define my own class that inherits most of the behavior from ons-back-button, but overrides just the stack navigation behavior (bring a page to the top of the stack rather than popping it)? I haven’t really worked with the new ES6 classes yet, so thought I’d ask here before trying that approach.

Here’s the current code I’m using for the back button:

document.querySelector('ons-back-button').onClick = function() {
   previous('page1.html');       
};

function previous(page){
    const prevNav = document.querySelector('#navigator');
    prevNav.bringPageTop(page);
}
      

And here’s the navigator element HTML:

<ons-splitter>
    <ons-splitter-side id="menu" side="left" width="220px" collapse swipeable>
        <ons-page>
            <ons-list>
                <ons-list-item onclick="fn.load('page1.html')" tappable>Vehicle Information</ons-list-item>
                <ons-list-item onclick="fn.load('page2.html')" tappable>Exterior Damage</ons-list-item>
                <ons-list-item onclick="fn.load('page3.html')" tappable>Glovebox Check</ons-list-item>
                <ons-list-item onclick="fn.load('page4.html')" tappable>Interior Check</ons-list-item>
                <ons-list-item onclick="fn.load('page5.html')" tappable>Road Test</ons-list-item>
                <ons-list-item onclick="fn.load('page6.html')" tappable>Lights Check</ons-list-item>
                <ons-list-item onclick="fn.load('page7.html')" tappable>Fluid Inspection</ons-list-item>
                <ons-list-item onclick="fn.load('page8.html')" tappable>Tire Inspection</ons-list-item>
                <ons-list-item onclick="fn.load('signature.html')" tappable>Signature</ons-list-item>
            </ons-list>
        </ons-page>
    </ons-splitter-side>
    <ons-splitter-content id="content">
        <ons-navigator animation="slide" animation-options="{ duration: 0.3 }" id="navigator" page="page1.html">        
        </ons-navigator>
    </ons-splitter-content>
</ons-splitter>

useParams Returns Undefined values

I’m using react-router-dom 5.2.0

App.jsx

`<Route path="/shop">
<ProductListPage />
</Route>
<Route path="/shop/:page">
<ProductListPage />
</Route>
<Route path="/shop/:gender/:category?">
<ProductListPage />
</Route>
<Route path="/shop/:filter">
<ProductListPage />
</Route>`

ProductListPage.jsx

`import { useParams } from "react-router-dom";

export default function ProductListPage() {
let { page } = useParams();
let { gender, category } = useParams();
let { filter } = useParams();

console.log(page + " " + gender + " " + filter + " " + category);

return (
<div className="bg-light-gray-1">
  <ProductCategories />
  <ProductList />
  <ClientList />
</div>
);
}`

Can’t get page or gender or anything, just undefined.

I have one page for listing all products.
Second one is for pagination
Third one is for categorization
And fourth one is for filtering

But variables where i get from links is not working. For example;
"/shop/women/tshirt" "/shop/man/shoe" "/shop/1

I’ve tried to get values like this but keep getting undefined values.

`import { useParams } from "react-router-dom";

export default function ProductListPage() {
let { page } = useParams();
let { gender, category } = useParams();
let { filter } = useParams();

console.log(page + " " + gender + " " + filter + " " + category);

How to apply data- attribute to rows from array of column headers

I have created a table in Angular using the column and row arrays at the bottom of this post. I have been trying to add a data-cell attribute to each row programmatically, which I have successfully done — I just can’t populate the attribute with data.

The desktop view is fine. On mobile devices, I am moving to a stacked version of the table (see image way at the bottom below the data) and I want to leverage the data-cell attribute to place the column headers above the appropriate cell data. If you look at the image, I want each column header to appear where the colons are currently appearing.

So far, I have the written this code. I just need a little help to get to the finish line, please and thank you.

const tds = Array.from(document.querySelectorAll('td'));

// Add data-cell attribute programatically
tds.forEach(td => {

  this.columns.forEach((col) => {
    console.log('HEADER: ', col.header);
    return col.header;
  })

  this.rows.forEach(row => {
    console.log('ROW: ', row)
    return row;
  })

  //td.setAttribute('data-cell', row.header)
})

=================================================================================

let columns: TableColumn[] = [
  {
    header: "Beverages",
    key: "name",
    sortable: true,
    cell: (item: any) => {
      return item.name;
    }
  },
  {
    header: "Cost",
    key: "cost",
    sortable: true,
    cell: (item: any) => {
      return item.cost;
    },
  },
  {
    header: "Text",
    key: "text",
    sortable: true,
    cell: (item: any) => {
      return item.text ? "Yes" : "No";
    },
  },
  {
    header: "Date",
    key: "date",
    sortable: true,
    cell: (item: any) => {
      return item.date;
    },
  },
  {
    header: "Unsortable",
    key: "unsortable",
    sortable: false,
    cell: (item: any) => {
      return item.unsortable;
    },
  }
]

let rows: any[] = [
  {
    id: 1,
    name: "Water",
    cost: 100,
    text: true,
    date: "05021967",
    unsortable: "12 Fountain Street, Andover, MA"
  },
  {
    id: 2,
    name: "Soda",
    cost: 250,
    text: false,
    date: "12121963",
    unsortable: "23 Oakland Avenue, Louisville, KY"
  },
  {
    id: 3,
    name: "Coffee/Tea",
    cost: 50,
    text: true,
    date: "03111964",
    unsortable: "4 Maple Road, Stone Mountain, GA"
  }
]

stacked version of my table for mobile devices

Error: Unable to resolve module missing-asset-registry-path with React Native app

I am trying to build a react native project and it is giving me an asset path error. I checked and double checked everything and I can not figure out why I am getting this issue.

here is the error:

info Dev server ready

i - run on iOS
a - run on Android
d - open Dev Menu
r - reload app

info Opening app on iOS...
info A dev server is already running for this project on port 8081.
info Found Xcode workspace "Grubber.xcworkspace"
info Found booted iPhone 15 Pro Max
info Building (using "xcodebuild -workspace Grubber.xcworkspace -configuration Debug -scheme Grubber -destination id=0C686315-2040-48D2-8D24-97C5F4422F75")
success Successfully built the app
info Installing "/Users/omarjandali/Library/Developer/Xcode/DerivedData/Grubber-fmzgeggnhellaudxvdkwklgxliav/Build/Products/Debug-iphonesimulator/Grubber.app on iPhone 15 Pro Max"
info Launching "app.grubber.grubber"
success Successfully launched the app on the simulator
 BUNDLE  ./index.js 

error: Error: Unable to resolve module missing-asset-registry-path from /Users/omarjandali/GrubberLLC/Grubber/src/Assets/Verified-icon.png: missing-asset-registry-path could not be found within the project or in these directories:
  node_modules
> 1 | �PNG
  2 | 
  3 | 
  4 | IHDR��>a�tEXtSoftwareAdobe ImageReadyq�e<�IDATx���U�0G���{H7�    &H�� �4� aؠ��l��+2$&;��?����cHBpt�e9�� �c�}�?��Gvqf�I�{[�_�� _�W��v�ti�LF    ��]�4�����t�W#��n   
                                                        �uK`��[|����_���%0��-��n    
                                                                                        �uK`��[���]
                                                                                                   =�eyV/��l�yqe�Z%'��~`��=���Ζk+�s�X�#��i�켋 ����7t�o^��HK�pu_
                                          ���zɩ���x�/[�o���"}�o>��v��5e';�>�&�g�瓚�BW��[��=2��0��@@� A@� A�w9���uݷ�(]mi5*�_��{geˏ�m8�w[�^R�����ʞn���,��� �p�%I0�?�7`�2�:�4B>�?�kY^���{�_�������(�u��
                                                                                   ���KL��?���/����ٺ;0��
    at ModuleResolver.resolveDependency (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:138:15)
    at DependencyGraph.resolveDependency (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/node-haste/DependencyGraph.js:231:43)
    at /Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/lib/transformHelpers.js:156:21
    at resolveDependencies (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/DeltaBundler/buildSubgraph.js:42:25)
    at visit (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/DeltaBundler/buildSubgraph.js:83:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 12)
    at async visit (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/DeltaBundler/buildSubgraph.js:92:5)
    at async Promise.all (index 3)
    at async visit (/Users/omarjandali/GrubberLLC/Grubber/node_modules/metro/src/DeltaBundler/buildSubgraph.js:92:5)

Here is my metro.config.js file:

const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const {
    resolver: { assetExts, sourceExts },
  } = await getDefaultConfig();

  return {
    transformer: {
      getTransformOptions: async () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: false,
        },
      }),
    },
    resolver: {
      assetExts: [...assetExts, 'png', 'jpg', 'jpeg'],
      sourceExts: [...sourceExts, 'jsx', 'js', 'ts', 'tsx'],
    },
  };
})();

I am importing the images here:

const Verified = require('../../Assets/Verified-icon.png');

The path to the images is correct and the file name is correct. It is just not accepting the image for some reason.

WordPress – On click of image carousel with lightbox, taking to image url and then showing lightbox

I have a wordpress website where I am using elementor Image Carousel in Blocksy theme. Here are the option I have selected for the images

  1. Link – Media File
  2. Lightbox – Yes

When I click on the image, first I am navigated to media url – /wp-content/uploads/image
and when I go back, I see the lightbox (default one with elementor) opened with the image in full screen.

Here, on click of a image, I want to just open the lightbox without navigating to /wp-content/uploads/image path. How can I achieve this?

I tried running the below jQuery and also similar php code using WP Code Light Plugin. also tried few chatgpt answers which didn’t work.

    // Ensure the script runs after the DOM is fully loaded
    $('.carousel a').on('click', function(e) {
        e.preventDefault(); // Prevent the default link behavior

        // Get the href attribute of the clicked link
        var href = $(this).attr('href');

        // Ensure the lightbox plugin is available and has a method to open images
        if (typeof $.featherlight === 'function') {
            $.featherlight(href); // Open the lightbox (replace with the correct method if using another plugin)
        } else {
            console.error('Featherlight plugin is not loaded or available.');
        }
    });
});

Please share share a solution for this? I am ok to use any free Carousel unless it supports Image view in full screen on click. Thanks!

Date.intlFormat hindi date does not show date in hindi which is 15 days and leter change the part of day

using Intl.dateTimeFormat() for indian month name and date

const fullHindi = {
    weekday: 'long',
    dayPeriod: 'long',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    dayPeriod: "narrow",
    hour: '2-digit',
    minute: '2-digit',
    second: 'numeric',
    calendar: 'indian',
    timeZone: 'Asia/Kolkata',
    numberingSystem: 'deva',
    formatMatcher: 'basic',
    hourCycle: 'h24',
};
const samay = new Intl.DateTimeFormat("hi", fullHindi);
const today = new Date();
const hindi = samay.format(today);
console.log({hindi}); // शक मंगलवार, २२ श्रावण १९४६, २३:४४:०८

but its not correct though its Shuka/Saptami शुक्ल सप्तमी i.e. in india date are till 15 and then it changes to diffrent paksha ( either Shukla/Krishna ) see more details here

so my ask is is there any format option configuration is there which change this; just like h12 and h24 format

React Form Not Submitting on onSubmit, But Works with onClick

I am trying to submit a login form in my React application. I have attached the loginUser function to the form’s onSubmit event. However, when I press the login button, nothing happens, and no errors are shown in the console.

Interestingly, if I move the loginUser function to the button’s onClick event, it works as expected. I want the form to be submitted via the form’s onSubmit event, not the button’s onClick event. What could be causing this issue?

const toggleButton = () => {
    console.log("Clicking toggle button");
    setIsLogin((prev) => !prev);
};

const loginUser = (e) => {
    console.log("I am Login Now...!");
    e.preventDefault();
};

<form
    style={{
        width: "100%",
        marginTop: "10px",
        marginBottom: "10px",
    }}
    onSubmit={loginUser}
>
    <TextField
        required
        fullWidth
        label="UsernameOrEmail"
        margin="normal"
        variant="outlined"
    />
    <PasswordInput />

    <Button
        fullWidth
        variant="contained"
        color="info"
        type="submit"
        sx={{
            marginTop: "10px",
            marginBottom: "10px",
            fontSize: "1.2rem",
            textTransform: "capitalize",
            fontWeight: "600",
            letterSpacing: "0.05rem",
            padding: "0.5rem 1rem",
        }}
    >
        Login
    </Button>

    <Typography
        textAlign={"center"}
        margin={"1rem"}
        fontWeight={"600"}
    >
        OR
    </Typography>

    <Button color="primary" fullWidth onClick={toggleButton}>
        Register Instead
    </Button>
</form>

I have started learning to create Routes in react but i am struck with a code where various contents of home page are not in a single component

As I stated that I have learned some basics of routing but there always a path defined "/" for home element whereas in my case I have many components of home page that is giving me a headache. I try to wrap them in app.jsx and then use them as home page but at both "http://localhost:5173" and "http://localhost:5173/about/" locations same app.jsx is rendering.

app.jsx

import Navbar from "./components/Navbar";
import HeroSection from "./components/HeroSection";
import FeatureSection from "./components/FeatureSection";
import Workflow from "./components/Workflow";
import Footer from "./components/Footer";
import Pricing from "./components/Pricing";
import Testimonials from "./components/Testimonials";
import { Outlet } from 'react-router-dom';

const App = () => {
  return (
    <>
      <Navbar />
      <div className="max-w-7xl mx-auto pt-20 px-6">
        <HeroSection />
        <FeatureSection />
        <Workflow />
        <Pricing />
        <Testimonials />
        <Footer />
        <Outlet />
      </div>
    </>
  );
};

export default App;

main.jsx

import React, { Children } from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import App from "./App"
import About from './components/About'

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: '/about',
        element: <About />,
      }
    ]
  }
])

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
)

I am expecting to create dynamic route as stated

Why Is My Code Producing Unexpected Results Despite Following Documentation?

I’m facing an issue where my code is producing unexpected results, even though I’ve followed the documentation and examples closely. I’ve reviewed my code multiple times and tried various debugging techniques, but I’m still unable to resolve the issue. Has anyone else encountered similar problems, and what strategies or solutions have you found effective in identifying and fixing such discrepancies?

Why Is My Code Producing Unexpected Results Despite Following Documentation?

in JavaScript navigator.clipboard.readText() is returning [object Promise] even though it is awaited [duplicate]

In the following example, highlight and copy “this is text”. That is what should be added to the clipboard. However [object Promise] is added instead. readText() is awaited so this is the incorrect result. How do I make this work?

<html>
This is text

<script>
document.addEventListener('copy', function (e) {
    var result = textCopied();
    e.clipboardData.setData('text/plain', result);
    e.preventDefault();
});

async function textCopied() {
var clipboardContents = await navigator.clipboard.readText();
return clipboardContents 
}
</script>
</html>

How to resovle – “Refused to execute inline script because it violates the following Content Security Policy”

I’m setting up Mixpanel in a simple chrome extension using Vanilla JS. I’m not using NPM but following this docs.

Below is my set-up where I pull in the Mixpanel SDK in the Index.html:

<!DOCTYPE html>
<html lang="en">
<head>

    <script type="text/javascript">
    <!-- Paste this right before your closing </head> tag -->
<script type="text/javascript">
  (function (f, b) { if (!b.__SV) { var e, g, i, h; window.mixpanel = b; b._i = []; b.init = function (e, f, c) { function g(a, d) { var b = d.split("."); 2 == b.length && ((a = a[b[0]]), (d = b[1])); a[d] = function () { a.push([d].concat(Array.prototype.slice.call(arguments, 0))); }; } var a = b; "undefined" !== typeof c ? (a = b[c] = []) : (c = "mixpanel"); a.people = a.people || []; a.toString = function (a) { var d = "mixpanel"; "mixpanel" !== c && (d += "." + c); a || (d += " (stub)"); return d; }; a.people.toString = function () { return a.toString(1) + ".people (stub)"; }; i = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split( " "); for (h = 0; h < i.length; h++) g(a, i[h]); var j = "set set_once union unset remove delete".split(" "); a.get_group = function () { function b(c) { d[c] = function () { call2_args = arguments; call2 = [c].concat(Array.prototype.slice.call(call2_args, 0)); a.push([e, call2]); }; } for ( var d = {}, e = ["get_group"].concat( Array.prototype.slice.call(arguments, 0)), c = 0; c < j.length; c++) b(j[c]); return d; }; b._i.push([e, f, c]); }; b.__SV = 1.2; e = f.createElement("script"); e.type = "text/javascript"; e.async = !0; e.src = "undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL ? MIXPANEL_CUSTOM_LIB_URL : "file:" === f.location.protocol && "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^///) ? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js" : "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"; g = f.getElementsByTagName("script")[0]; g.parentNode.insertBefore(e, g); } })(document, window.mixpanel || []);
</script>
</head>
<body>
    <script type="module" src="popup.js"></script>
</body>
</html>

Within my popup.js I reference the below

 //Import Mixpanel SDK
import mixpanel from "mixpanel-browser";
 
// Near entry of your product, init Mixpanel
mixpanel.init("0000", {
  debug: true,
  track_pageview: true,
  persistence: "localStorage",
});

I see the following errors in the console when I check to see if Mixpanel object exist

  index.html:12 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-6VDlGRSSdUDK2nuG1Ys7GZ0tuFVwEcvszIXy9+2ULI4='), or a nonce ('nonce-...') is required to enable inline execution.

index.html:12 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Either the 'unsafe-inline' keyword, a hash ('sha256-6VDlGRSSdUDK2nuG1Ys7GZ0tuFVwEcv'), or a nonce ('nonce-...') is required to enable inline execution.

index.html:1 Uncaught TypeError: Failed to resolve module specifier "mixpanel-browser". Relative references must start with either "/", "./", or "../".

how to limit requests made by webworker in angular

Currently in my Angular project we upload batches of files using the webworker. It turns out that the webworker can make up to six requests at a time (depending on the browser from what I’ve read on other forums), however my backend only processes one request at a time, so depending on the processing time to return the response to the frontend ( despite being a promise) ends up exceeding the waiting time.

As a stopgap, I added a 1-second timeout between requests on the frontend so the backend had enough time to process and return the response.

What I would like to know is if I can reduce these simultaneous requests from the webworker? For example, instead of 6 requests at the same time, limit it to 3?

F11 StepInto just goes to next line in VSCode DEV 1.93.0

I am trying to follow the https://github.com/microsoft/vscode/wiki/How-to-Contribute
steps to Build, to Run, and then to Debug.
I built into C:H_Paulvscode1930 It has product.json “nameShort”: “Code – OSS”
and package.json “name”: “code-oss-dev”, “version”: “1.93.0”,

My app (Pencil) has package.json with “main”: “index.js”, part of index.js is

BP1 L90    var mainUrl = "file://" + __dirname + "/app.xhtml";
BP2 L91    mainWindow.loadURL(mainUrl);
BP3 L92    mainWindow.show();

I then enter BP (breakpoint) on those lines.
When it breaks at Line 91, I want to F11 StepInto vscode1930
and then F10 single step to see whats happening to the app’s source code

But F11 just continues with Pencil Line92.

Below are launch.json-s for vscode1930 and for Pencil:

//  vscode1930-launch.txt   from  launch.js   expanded for the compound item.
    {
        "name": "VS Code",
        "stopAll": true,
        "debugStdLib":true,
        "configurations": [
            "Launch VS Code Internal",
            "Attach to Main Process",
            "Attach to Extension Host",
            "Attach to Shared Process",
        ],
        "preLaunchTask": "Ensure Prelaunch Dependencies",
        "presentation": {
            "group": "0_vscode",
            "order": 1
        }
    },
//====================================================
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch VS Code Internal",
            "windows": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.bat"
            },
            "osx": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.sh"
            },
            "linux": {
                "runtimeExecutable": "${workspaceFolder}/scripts/code.sh"
            },
            "port": 9222,
            "timeout": 0,
            "env": {
                "VSCODE_EXTHOST_WILL_SEND_SOCKET": null,
                "VSCODE_SKIP_PRELAUNCH": "1"
            },
            "cleanUp": "wholeBrowser",
            "runtimeArgs": [
                "--inspect-brk=5875",
                "--no-cached-data",
                "--crash-reporter-directory=${workspaceFolder}/.profile-oss/crashes",
                // for general runtime freezes: https://github.com/microsoft/vscode/issues/127861#issuecomment-904144910
                "--disable-features=CalculateNativeWinOcclusion",
                "--disable-extension=vscode.vscode-api-tests"
            ],
            "userDataDir": "${userHome}/.vscode-oss-dev",
            "webRoot": "${workspaceFolder}",
            "cascadeTerminateToConfigurations": [
                "Attach to Extension Host"
            ],
            "pauseForSourceMap": false,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "browserLaunchLocation": "workspace",
            "presentation": {
                "hidden": true,
            },
            // This is read by the vscode-diagnostic-tools extension
            "vscode-diagnostic-tools.debuggerScripts": [
                "${workspaceFolder}/scripts/hot-reload-injected-script.js"
            ]
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Main Process",
            "timeout": 30000,
            "port": 5875,
            "continueOnAttach": true,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ],
            "presentation": {
                "hidden": true,
            }
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "restart": true,
            "name": "Attach to Extension Host",
            "timeout": 0,
            "port": 5870,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js",
                "${workspaceFolder}/extensions/*/out/**/*.js"
            ]
        },
//=========================================
        {
            "type": "node",
            "request": "attach",
            "restart": true,
            "name": "Attach to Shared Process",
            "timeout": 0,
            "port": 5879,
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
            ]
        },
//=========================================
// Pencil launch.json
{
    "justMyCode": false,
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Electron: Main",
            "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
            "windows": {
                "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
            },
            "runtimeArgs": [
                "."
            ],
            "trace": true,            
            "env": {
                "VSCODE_DEBUG_MODE": "true"
            },
            "sourceMaps": true,
            "cwd": "${workspaceFolder}",
            "outputCapture": "std",  
            "outFiles": [ "${workspaceFolder}/out/**/*.js" ],  
            "localRoot": "${workspaceFolder}"
        }
    ]
}

Parsing ‘s in JSON throws bad control character in string literal error

I am using WinDEV Mobile to dynamically build Javascript controls. I have a problem when new lines or * is used within the JSON. When I remove them, the following code works:

const json = `[{"id":1,"data":{"visible":true,"visibleFunction":"","repeatCount":1,"required":"false","readOnly":false},"text":"Some RandomnnWords With a \nnAnd new lines","type":"textbox"}]`;

console.log(JSON.parse(json));

However, when they’re left in there, the error I receieve is the following due to the escaped * characters:

SyntaxError: JSON.parse: bad control character in string literal

I have no control on WinDEV Mobile to alter how this is passed in as it doesn’t support many JSON functions to change this and I need to support the new lines.

I originally tried to do a .replace() to convert any to \ but the issue is, this JSON definition can have Base64 images inside of it which then fails to parse.

Is there anything I can do in Javascript to prevent the unescaping of the n and \?