HERE Maps CSP error on Safari browser: blobs can’t be loaded

I am working on a webpage which integrates the JAVASCRIPT HERE MAPS SDK which works fine so far. For security reasons, we now introduced CSP to the website. Ever since that, HERE maps don’t work properly on Safari browser anymore. The map canvas as such is loaded but remains gray with no map details nor working controls. According to the browser console/inspector, several blobs can’t be loaded due to CSP violations.

I have not been fiddling around for hours to get the right CSP settings inside my HTML META tag but I just won’t get it working on Safari browser. For debugging reasons, I even tried a very unsafe solutions which pretty much “allows everything” just to get it working, but even with this code, the blobs remain blocked:

<meta http-equiv="Content-Security-Policy" 
    content="default-src * data: gap: content: mediastream: blob: filesystem: about: ws: wss: 'unsafe-eval' 'wasm-unsafe-eval' 'unsafe-inline';
      child-src 'self' data: mediastream: blob: filesystem: about: ws: wss: 'unsafe-eval' 'wasm-unsafe-eval' 'unsafe-inline';
      worker-src 'self' data: gap: content: mediastream: blob: filesystem: about: ws: wss: 'unsafe-eval' 'wasm-unsafe-eval' 'unsafe-inline'; 
script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; 
connect-src * data: blob: 'unsafe-inline'; 
object-src * data: blob: filesystem: 'unsafe-inline' 'unsafe-eval' ;
img-src * data: blob: 'unsafe-inline'; 
frame-src * data: blob: ; 
style-src * data: blob: 'unsafe-inline';
font-src * data: blob: 'unsafe-inline';
frame-ancestors * data: blob: 'unsafe-inline';">

Anyone else experiencing this or might have a clue, what I might be missing?

Why is my value being evaluated as undefined in Vue.js?

I’m encountering an issue while refactoring my navbar in Vue.js. Originally, I had it running outside my app.component, but now, after compressing and organizing it within my app.component along with the corresponding method and value assignment, the ‘theme’ value is being recognized as undefined.

Here’s my code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue Basics</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://unpkg.com/vue@3"></script>
</head>
<body>

<navbar
    :pages="pages"
    :active-page="activePage">
</navbar>


<page-viewer
        :page="pages[activePage]"
></page-viewer>


<script>
    let app = Vue.createApp({
        data() {
            return {
                activePage: 0,
                pages: [
                    {
                        link: {text: 'Home', url: 'index.html'},
                        pageTitle: 'Home',
                        content: 'This is the Home Content'
                    },
                    {
                        link: {text: 'About', url: 'about.html'},
                        pageTitle: 'About',
                        content: 'This is the About Content'
                    },
                    {
                        link: {text: 'Contact', url: 'contact.html'},
                        pageTitle: 'Contact',
                        content: 'This is the Contact Content'
                    }
                ]
            };
        }

    });

    app.component('page-viewer', {
        props: ['page'],
        template:
            `
            <div className="container">
                <h1>{{page.pageTitle}}</h1>
                <p>{{page.content}}</p>
            </div>
            `

    });

    app.component('navbar', {
        props: ['pages', 'activePage'],
        data() {
            return {
                theme: 'light'
            }
        },

        methods: {
            changeTheme() {
                let theme = 'light';
                if (this.theme == 'light')
                {
                    theme = 'dark';
                }
                this.theme = theme;
            }
        },
        template:
        `
          <nav class="navbar navbar-expand-lg"
               :class="[`navbar-${theme}`,`bg-${theme}`, 'navbar', 'navbar-expand-lg']">
          <div class="container-fluid">
            <a href="#" class="navbar-brand">My Vue</a>
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
              <li v-for="(page, index) in pages" class="nav-item" :key="index">
                <a :href="page.link.url"
                   :title="`This link goes to the ${page.link.text} page`"
                   @click.prevent="activePage = index"
                   aria-current="page"
                   class="nav-link"
                   :class="{active: activePage == index}"

                >{{ page.link.text }}</a>
              </li>
            </ul>

            <form class="d-flex">
              <button class="btn btn-primary"
                      @click.prevent="changeTheme()">
                Toggle Button
              </button>
            </form>
          </div>

          </nav>
        `

    })

        app.mount('body')
</script>

</body>
</html>

Looking for a better Double-Submission Solution

The following code solved an issue that occurred using a session variable, but then it caused another problem.

Problem A (Critical): Users A & B were participating in a group discussion. Both users were using the same web page (The Page) to change an attributes (The Attribute) of a part (The Part) by clicking on a button (The Edit Button), setting a value and saving it. So, in the discussion, User A changed The Attribute and saved it to Text_A. Then the group decided the value should be different, and User B changed it to Text_B. User A wanted to see Text_B, so clicked the Refresh (Chrome: Reload) button and clicked “Continue” on the Popup Resubmission warning (below). User A’s action unknowingly re-committed Text_A (Double-Submit Problem).

Solution A: Code below.

Problem B (Annoyance): Later, I opened The Page for Part A. Then I immediately opened The [Same] Page for Part B in another browser tab FROM THE SAME WEB SERVER (necessary for session state to be same in both pages). I then returned to Part A, clicked The Edit Button. The Page redirected to itself and stayed in Read Only mode. I clicked The Edit Button again and The Page entered Edit Mode. The cause of the Redirect was: When The Page was opened in another tab for Part B, it changed the Session Variable. If I had not opened Part B, the ViewState and Session variables in the Part A page would have stayed equal when The Edit Button was clicked the first time. But after opening Part B, they became Not Equal. That difference caused execution of the Redirect command back to Read Only mode again. Solution A caused Problem B.

How can Problem A be solved with a different solution (Solution B) that WILL NOT cause Problem B?

Is there an easy Java_Script or Ajax solution?

I’ve seen a fragmented C# solution involving creating a new Page class that inherits System.Web.UI.Page but I had do far been unsuccessful filling in the missing pieces. With that solution, my web page (Class Part) would, instead of inheriting the System version, would instead inherit the new Page class.

Solution A Code:

protected void Page_Load(object sender, EventArgs e)
{
  handlePageRefreshed(IsPostBack, ViewState, Session, Request);
}

private void handlePageRefreshed(bool isPostBack,StateBag inViewState, HttpSessionState inSession, HttpRequest inRequest)
{
  if (isPostBack)
  {
    if (inViewState["postGuid"].ToString() != inSession["postGuid"].ToString())
    {
      Response.Redirect(inRequest.Url.AbsoluteUri);
    }
    else
    {
      inSession["postGuid"] = System.Guid.NewGuid().ToString();
      inViewState["postGuid"] = inSession["postGuid"].ToString();
    }
  }
  else
  {
    inViewState["postGuid"] = System.Guid.NewGuid().ToString();
    inSession["postGuid"] = inViewState["postGuid"];
  }
}

Things I found in search of Solution B but I couldn’t tell if therein lied the solution since I’m weak with JavaScript & Ajax, and the new Page class solution was fragmented:

Render React Component at top

I’m new to React, but I couldn’t find anything online about it. I don’t understand what exactly the error is. First of all, I have a PageComponent.

This PageComponent has (relevant to this question) a function called forceAddComponent. This takes componentData and data as parameters.

The componentData is a dictionary that looks like this:

{
    name: 'SomeComponentNameAsString',
    ref: referenceToAnExamComponent,
    component: <...Component/>
}

and you can see the data. However (no matter how I try), the new component is ALWAYS added at the bottom, not at the top of the other examComponents. I have tried unshift and also built new lists. Nothing has helped. Do any of you have an idea why React just renders it below the last one anyway?

The PageComponent.js:

import {Component, createRef} from "react";

export class PageComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            examComponents: [] // componentData
        }

        this.pageRef = createRef();
    }

    render() {
        return (
            <div className={'paper a4'} ref={this.pageRef}>
                {this.state.examComponents.map((componentData, _index) => {
                    return componentData.component;
                })}
            </div>
        )
    }

    scrollToPage() {
        // scroll to paper
        const top = this.pageRef.current.offsetTop;
        window.scrollTo({
            top: top - 80,
            behavior: 'smooth'
        });
    }

    getSumOfHeightPagePadding(page) {
        const pageStyle = window.getComputedStyle(page);
        return parseInt(pageStyle.paddingTop) + parseInt(pageStyle.paddingBottom);
    }

    getRemainingHeight() {
        const maxHeight = this.getMaxHeight();
        const usedHeight = this.getUsedHeight();
        return maxHeight - usedHeight - this.getSumOfHeightPagePadding(this.pageRef.current);
    }

    tryAddComponent(componentData) {
        const maxHeight = this.getMaxHeight();
        // render component and wait for it to be rendered
        // this.pushComponent(component);
        const r = async () => {
            await this.pushComponent(componentData);

            const componentHeight = componentData.ref.current.getActualHeight();

            // check if component fits on page
            if (this.getUsedHeight() >= maxHeight) {
                // component is too big for this page
                // remove component from page
                this.popComponent(componentData.component);
                return {status: false, neededHeight: componentHeight};
            }

            return {status: true, neededHeight: componentHeight};
        };
        return r();
    }

    getMaxHeight() {
        // get max height of this page
        const pageStyle = window.getComputedStyle(this.pageRef.current);
        let height = parseInt(pageStyle.height);
        height -= this.getSumOfHeightPagePadding(this.pageRef.current);
        return height;
    }

    getUsedHeight = () => {
        // get height of all components in this page
        let height = 0;
        Object.keys(this.state.examComponents).forEach((key, _index) => {
            const component = this.state.examComponents[key];
            height += component.ref.current.getActualHeight();
        });
        return height;
    }

    forceAddComponent = async (componentData, data = {atTop: true}) => {
        await this.pushComponent(componentData, data);
    }

    getActualHeight() {
        // get height of this page
        return this.pageRef.current.clientHeight;
    }

    pushComponent(componentData, data = {atTop: false}) {
        return new Promise(resolve => {
            const newExamComponents = this.state.examComponents;
            if (data.atTop) {
                newExamComponents.unshift(componentData);
            } else {
                newExamComponents.push(componentData);
            }

            this.setState({examComponents: newExamComponents}, () => {
                resolve();
            });
        });
    }

    popComponent(component) {
        this.setState(prevState => ({
            examComponents: prevState.examComponents.filter((_, index) => {
                return component !== this.state.examComponents[index].component;
            })
        }));
    }
}

Why does jshint warn of calling functions from a function declared within a loop?

The following code

function foo () {}

let data = [];

for (let x of data)
{
  x.bar = function ()
  {
    foo ();
  };
}

causes this warning in jshint

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (foo)

I am aware that Javascript has unintuitive rules for binding variables to functions created in a loop. For example (if I’ve got this right) the following code causes each function object to bind to the same table

for (let table of document.getElementsByTagName ("table"))
{
  table.my_function = function ()
  {
     do_something_with (table);
  };
}

I think jshint is treating these two cases as equally suspicious. But they look different to me. Is this warning something to take seriously, or is jshint being overly paranoid?

State is undefined for some paths of a json source in Pinia [duplicate]

I am following along a course which uses Vuex or Pinia, the Pinia version is not delivered for this part. I source a data.json but only one path is defined it seems (users), the others (threads and posts) seem to be undefined.

Top level structure of the data.json

enter image description here

The user store

import sourceData from '@/data.json'

export const useUserStore = defineStore('UserStore', {
  state: () => {
    return {
      ...sourceData,
      authId: '38St7Q8Zi2N1SPa5ahzssq9kbyp1'
    }
  },
  getters: {
    authUser: state => state.users.find(u => u.id === state.authId),
    posts: state => state.posts.filter(p => p.userId === state.authId),
    postsCount: state => this.posts(state).length,
    threads: state => state.threads.filter(t => t.userId === state.authId),
    threadsCount: state => this.threads(state).length
  }
})

Vue DevTools of the UserStore (as JSON)

{"authUser":{"avatar":"https://avatars3.githubusercontent.com/u/2327556?v=4&s=460","email":"[email protected]","lastVisitAt":1594772078,"name":"Chris Fritz","isModerator":true,"registeredAt":1594632260,"username":"chrisvfritz","usernameLower":"chrisvfritz","id":"38St7Q8Zi2N1SPa5ahzssq9kbyp1"},"threadsCount":"[native Error Cannot read properties of undefined (reading 'threads')<>TypeError: Cannot read properties of undefined (reading 'threads')n    at Proxy.threadsCount (http://localhost:5173/src/stores/UserStore.js:16:33)n    at ReactiveEffect.fn (http://localhost:5173/node_modules/.vite/deps/pinia.js?v=b36d8af7:986:30)n    at ReactiveEffect.run (http://localhost:5173/node_modules/.vite/deps/chunk-FVTSMHLH.js?v=b36d8af7:422:19)n    at get value [as value] (http://localhost:5173/node_modules/.vite/deps/chunk-FVTSMHLH.js?v=b36d8af7:1370:35)n    at MutableReactiveHandler.get (http://localhost:5173/node_modules/.vite/deps/chunk-FVTSMHLH.js?v=b36d8af7:695:61)n    at http://localhost:5173/node_modules/.vite/deps/pinia.js?v=b36d8af7:526:39n    at Array.reduce (<anonymous>)n    at http://localhost:5173/node_modules/.vite/deps/pinia.js?v=b36d8af7:524:37n    at Array.forEach (<anonymous>)n    at http://localhost:5173/node_modules/.vite/deps/pinia.js?v=b36d8af7:495:36]"}

I was expecting that state.threads and state.posts is defined exactly as state.users is but obviously I am missing something.

How to set a value on a React TextField with handlechange?

I need to set a value after pressing a button on this textfield :

<TextField
fullWidth
inputProps={{ maxLength: 75 }}
key="nomeSocial"
id="outlined-basic"
label="Nome Social"
name="nomeSocial"
onChange={(handleChange)}
value={values.nomeSocial}
variant="outlined"
/>

I’ve tried to set the value by the comand document.getElementsByName("nomeSocial")[0].value = "..."

but the field get this way:
enter image description here

and when I click somewhere the input gets empty.

is there any way to change a value of a input by javascript and have the TextField reconize it as if someone had typed it?

Why is my state crushing by action of filtering the elements of it?

import React from 'react'
import { TTodo } from './types/data'
import TodoList from './components/TodoList'

const App:React.FC = () => {
  const [value, setValue] = React.useState('')
  const [todos, setTodos] = React.useState<TTodo[]>([])
  const [valuePrev, setValuePrev] = React.useState('')

  const inputRef = React.useRef<HTMLInputElement>(null)
  
  const addTodo = ():void =>{
    if(inputRef.current){
      if(inputRef.current.value !== valuePrev){
        console.log(true)
        if(value){
          setTodos([...todos, {
            id:Date.now(),
            title: value,
            complete: false
          }])
          setValuePrev(value)
          setValue('')
          setTodos(todos.filter((item, index)=> index = todos.findIndex(elem=> elem.title === item.title)))
        }
      }
    }
  }
  return (
    <div>
      <input ref={inputRef} className="text" value={value} onChange={e=>setValue(e.target.value)}></input>
      <button onClick={()=>{addTodo()}}>add</button>
      <TodoList  items={todos}/>
    </div>
  )
}

export default App

This filter((item,index) …) eliminates the duplicated instances of an objects in the array of objects (state in that case),this works completely fine, when Im trying to use it with another arrays like this ~[{title:’smt’},{title:’smt’}]~,but when it comes to state everything refuces to work propely. The problem is in the state mutation and if it is, what can I do with that?

Nested route is showing white blank screen in react-router-dom

I am trying to implement a URL like /user/info, but when I hit the URL, it shows a white blank screen. I have tried to resolve this issue, but unfortunately, I am not able to do so. I will attach my code as well to show what I have tried. Any support would be much appreciated. Thanks.

Routes

import React from "react";
import { AppLayout } from "ui";
import { AppRoute } from "types";
import Dashboard from "pages/dashboard/index";
import InfoScreen from "pages/vendor/dashboard";

const routes: AppRoute[] = [
  {
    path: "/user",
    component: Dashboard,
    exact: true,
    layout: AppLayout,
    indexRoute: true,
    children: [
      {
        path: "/info",
        component: InfoScreen,
        exact: false,
        layout: AppLayout,
        indexRoute: false,
        children: [],
      },
    ],
  },
];

export default routes;

Render Component

<StylesProvider>
    <Router>
      <div className="app bg-body">
        <OktaProvider>
          <AuthProvider>
            <Provider store={store}>
              <Routes>
                {routes.map((route, index) => {
                  return (
                    <Route
                      key={index}
                      path={route.path}
                      element={
                        route.layout ? (
                          <route.layout appName="Envio" />
                        ) : (
                          <Wrapper />
                        )
                      }
                    >
                      <Route
                        key={index}
                        path={route.path}
                        index={route.indexRoute ? true : undefined}
                        element={<route.component />}
                      />
                      {route.children?.map((child, index) => (
                        <Route
                          key={index}
                          path={child.path}
                          index={route.indexRoute ? true : undefined}
                          element={<child.component />}
                        />
                      ))}
                    </Route>
                  );
                })}

              </Routes>
            </Provider>
          </AuthProvider>
        </OktaProvider>
      </div>
    </Router>
  </StylesProvider>

CSS wont effect a className of an object created in a loop

I am currently trying to have 10 horizontal lines that I have created be styled with CSS. They appear on the screen but I can’t seem to have CSS affect them. The class name I have given them is “horizontal”.

REACT.JS CODE

import React from "react";
import "./home.css";
import myPicture from "../../assets/picofme.png";

const HorizontalLines = ({ numberOfLines }) => {
  const lines = [];

  for (let i = 0; i < numberOfLines; i++) {
    lines.push(<hr key={i} className="horizontal" />);
  }

  return <div>{lines}</div>;
};

const Home = () => {
  return (
    <section id="home">
      <div className="homeContent">
        <span className="hi">Hello,</span>
        <span className="intro">
          I'm <span className="Me">Me</span>
          <br />
          software
        </span>
        <p className="introPara">
         This is my experince
          developer.{" "}
          <p>Here are my solutions</p>
        </p>
      </div>
      <img src={myPicture} alt="profile" className="myPicture" />
      <HorizontalLines numberOfLines={10} />
    </section>
  );
};

export default Home;

MY CSS CODE

#home {
  height: calc(100vh - 4rem);
  width: 100%;
  max-width: 98%;
  margin: 0 auto;
  overflow: hidden;
  position: relative;
}

.horizontal {
  z-index: -4;
  color: #22c8ff;
}

All the other classNames are being used in the CSS code but I am unable to show them.

Why it doesn’t work (if-else in typescript)

  onTicketProcess = async (id: number) => {

    const groupId = this.ticketService.getGroupIdByTicketId(id)
    const ticket = await 
        this.glpi.getTicket(this.glpiSessionToken, id)
    console.log ("TICKET_STATYS!!!!!!!!!!!!", ticket.status)
    var ticket_status = ticket.status

    if (ticket_status = 3) {
  
      await this.telegram.sendGroupMessage(`❗️<strong>Заявка в процессе;</strong> `, {
        reply_to_message_id: groupId,
        parse_mode: 'HTML'
      })
 
    }
    else (console.log("status is else"))
  }

I want this to send message if the status is 3.

error net::ERR_ABORTED 404 (Not Found) in import/export in javaScript

I have a very javascript project

There are two js files in the project

enter image description here

I have exported a function in template.js

enter image description here

And in another file, which is my main file, which I addressed in
the html, I import that function and use it.

enter image description here

Now the project execution time gives this error

GET http://127.0.0.1:5501/template net::ERR_ABORTED 404 (Not Found)

enter image description here

I hope I explained my problem well

I found a similar error at this address

Import/Export in Javascript, I get a “net::ERR_ABORTED 404 (Not Found)”

But there was no detailed explanation about the problem and how to fix the problem
I tried to explain my problem in detail

Thank you very much for helping me with this error

Why isn’t bluetooth sending the message?

I’m trying to send bytes to my device that runs on python to display the message.

const sendStringToDevice = async () => {
        try {
          // Request Bluetooth device
          const device = await navigator.bluetooth.requestDevice({
            filters: [{ name: 'monocle' }],
            optionalServices: [0x2A00],
          });
      
          // Connect to the device
          const server = await device.gatt.connect();
      
          // Get the specified service
          const service = await server.getPrimaryServices();
          console.log("service got")
      
          // Get the specified characteristic
          const characteristic = await service.getCharacteristic();
      
          // Convert the string to a UInt8Array (assuming ASCII encoding)
          const encoder = new TextEncoder('utf-8');
          const data = encoder.encode(message);
      
          // Send the data to the characteristic
          await characteristic.writeValue(data);
      
          console.log(`String "${message}" sent successfully to monocle`);
        } catch (error) {
          console.error('Error sending string to Bluetooth device:', error);
        }
      };

I tried to restart the application and run it again but nothing. It’s going to a python file from javascript so I am not sure if that affects anything. When it runs neither the console.log(String "${message}" sent successfully to monocle); or console.error(‘Error sending string to Bluetooth device:’, error); run.

It’s stuck in limbo and I don’t know why!

Why does this function only output the second value? Is there any way for a function to output two outputs? [duplicate]

I’m new to Javascript, but have experience with other languages. I was trying to get a function to give me two outputs but it wasn’t working, and ultimatley with the syntax I was using, I discovered that it was only giving me the second value I inputed. Is there a reason for this? I can’t think of any way that you would want to use this type of syntax if the first value is ignored entirely.

My code:

var a;
    
var b;
var c;
    
var d = false;
var e = "";
    
var f = "";
    
var g = false;

a = returnTwoValues();
console.log("A: " + a);
    
b, c = returnTwoValues();
console.log("B: " + b);
console.log("C: " + c);
    
d, e = returnTwoValues();
console.log("D: " + d);
console.log("E: " + e);
    
f = returnTwoValues();
console.log("F: " + f);
    
g = returnTwoValues();
console.log("G: " + g);

function returnTwoValues(){
  return true, "Hello";
}

It’s Output:

"A: Hello"
"B: undefined"
"C: Hello"
"D: false"
"E: Hello"
"F: Hello"
"G: Hello"

the same thing was outputted when i changed returnTwoValues() to

function returnTwoValues(){
  return "Hi", "Hello";
}