Chrome Extension “Refused to load the JavaScript URL because it violates the following Content Security Policy directive.”

Link to extension: https://chrome.google.com/webstore/detail/pojodomdlpobompicdllljgiomnfpmho

Link to development version: https://github.com/misswell/octoman-weibo-backup

Problems:
To use this plugin, you need to login into your Weibo account first, otherwise, there will appear a line of text as shown in the screenshots below: “验证出错,请点击此链接,然后返回重试。(Error in verification, please click this link and then return to retry.)”
Under normal circumstances, after logging in and refreshing the page, this line of text will disappear, and “立即停止 (Stop Now)” will turn into “下载 (Download)”, then it works normally.
I have been using it for more than a year without problems, but recently I don’t know if it’s because of Chrome update, this line of text can’t be removed in any way.
enter image description here

The whole description of the error:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: “script-src ‘self’ blob: filesystem:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the ‘unsafe-hashes’ keyword is present.
Context
popup.html
Stack Trace
popup.html:1 (anonymous function)
enter image description here

I’ve tried to added “”content_security_policy”: “script-src ‘self’ “, but it didn’t work.

How to get the ones that don’t have a user_id field? Mongoose Node

How to get those for which user_id is missing?
I want to get the number of those who do not have user_id

My code

 const data = await configSchema.aggregate([
      {
        $set: {
          new_id: {
            $toString: "$_id",
          },
        },
      },
      {
        $lookup: {
          from: "gds",
          localField: "new_id",
          foreignField: "cnf_id",
          as: "gds_items",
        },
      },
      { $unset: ["availability"] },
      { $addFields: { availability: { $size: "$gds_items" } } },
      { $unset: ["gds_items", "new_id"] },
    ]);

gdsSchema
gds

ConfigSchema
ConfigSchema

Aggregation Output
Output

How to fix no provider for localStorage and circular dependency

I have an angular frontend project generated with nrwl nx. After implementing an interceptor I am getting the following two errors after trying to make a request:

The first call causes this one:

ERROR NullInjectorError: R3InjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> LocalStorageService -> LocalStorageService -> LocalStorageService]: 
  NullInjectorError: No provider for LocalStorageService!

THe second call of the same request right after the first one causes this one:

ERROR Error: NG0200: Circular dependency in DI detected for InjectionToken HTTP_INTERCEPTORS. Find more at

The funny thing is I have provided my interceptor in my app.module, I thought this was enough and the second error confuses me greatly as I did not import or use the interceptor directly. I hope someone here can help me out:

App-module:

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NbLayoutModule,
    LoginComponentModule,
    DashboardModule,
    AppRoutingModule,
    NbThemeModule.forRoot({name: 'default'}),
    NbLayoutModule,
    NbEvaIconsModule,
    MatToolbarModule,
    MatIconModule,
    MatButtonModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true,
    }

  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

interceptor:

@Injectable({providedIn: "root"})
export class AuthInterceptor implements HttpInterceptor {

  constructor(private localStorage: LocalStorageService, private sessionStorage: SessionStorageService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url || (request.url.startsWith('http') && !(environment.rootUrl && request.url.startsWith(environment.rootUrl)))) {
      return next.handle(request);
    }
    const token =
      this.localStorage.retrieve('token') ||
      this.sessionStorage.retrieve('token');
    if (token) {
      request = request.clone({
        setHeaders: {
          Authorization: 'Bearer ' + token,
        },
      });

    }
    return next.handle(request);
  }
}

I have other modules but as far as I understand if I provided it in the app-module it should be enough, at least I thought so. I hope you guys can help me out

setState not updating react component properly

I am trying to add Pagination in React and sending query for it, based on page number of the url. The data should be fetched and update the same component. But the problem occurs when I go from page 2 to page 3. The data from page 2 data and page 3 data are shown alternatively for a while.

enter image description here

After some time the newly fetched data is updated
I have setPost([]) after page 3 is clicked, but I don’t from where page 2 is coming.
I want to setLoading true till the newly fetched data is completely fetched.

const Daily = ({match}) => {

    const [posts, setPosts] = useState([]);
    const [numberOfPages, setNumberOfPages] = useState([]);
    const [loading, setLoading] = useState(true);
    const perPageItems = 8;

    useEffect(() => { 
        const totalPost = () => {
            getPostsCount()
            .then(data => {
                setNumberOfPages(Math.ceil(data/perPageItems))
            })
        }

        const loadIndexPosts = (a, b) => {
            getPostsByIndex(a, b)
            .then(data => {
                if (data.error) {
                    console.log(data.error);
                } else {
                    setPosts(data);
                }
                setLoading(false);
            })
        };

        totalPost()
        if(match.params.page==undefined)
            match.params.page=1;
         var n = parseInt(match.params.page)-1;
         var startIdx = n*perPageItems;
         loadIndexPosts(startIdx, perPageItems)
    },)
    
    console.log(posts);

    return (

        <div>
            <div className="mt-5 daily-card-feed">
                {loading && <ThreeDotsWave/>}
                {posts.map((post, index) => {
                    return (
                        <div key={index}>
                            <DailyCard post={post}/>
                        </div>
                    )
                })}
            </div>

            
            <div className="h4 pb-5 pull-right mr-5">
                {match.params.page==1 &&
                    <Link to={`/daily/page/2`} onClick={() => {setLoading(true); setPosts([])}}>Older Post -></Link>}
                {match.params.page!=1 &&
                     <Link to={`${parseInt(match.params.page)+1}`} onClick={() => {setLoading(true); setPosts([])}}>Older Post -></Link>}
            </div>

        </div>
    )

}

Getting a function from an express server and running it in a webpage via a script tag

How do you return a function from an express server and run it in a browser?

I have hosted a function on Google Cloud Platform (Cloud Functions) and want to run it in a web application via a script tag. The function is in Nodejs 16 and can be called via https, and is a simple hello world example:

exports.helloWorld = () => {
  const widget = console.log("This is a widget");
  return widget();
}

However, it seems as though I cannot call it that way, because I get an Error: could not handle the request and a 500 status message each time I try to hit the endpoint.

I want to be able to embed this function on a website via something like:

<script src="https://example.com/function-name"/>

How can I achieve that?

Particle.js not showing particles on ReactJS website

I have been trying to implement Particles.js on my portfolio website but have been rather unsuccessful. This is the following line of code I have run in my library to get it running:

npm i react-tsparticles

I couldn’t add this package to my website so i tried to add this to a new project. i tried 2 different tutorial video to add it but it didn’t work out. These are the videos
https://www.youtube.com/watch?v=F20SxgG5MlM
https://www.youtube.com/watch?v=NO76xNYkNGk&t

This is how my page looks right now

This is how my page should look

This is my configuration file for particles

const particlesConfig = {
  background: {
    color: "#6f32a8"
  },
  fullScreen: {
    enable: true,
    zIndex: -1
  },
  particles: {
    number: {
      value: 80,
      density: {
        enable: true,
        value_area: 800
      }
    },
    color: {
      value: "#ffffff"
    },
    shape: {
      type: "circle",
      stroke: {
        width: 0,
        color: "#000000"
      },
      polygon: {
        nb_sides: 5
      },
      image: {
        src: "img/github.svg",
        width: 100,
        height: 100
      }
    },
    opacity: {
      value: 0.5,
      random: false,
      anim: {
        enable: false,
        speed: 1,
        opacity_min: 0.1,
        sync: false
      }
    },
    size: {
      value: 3,
      random: true,
      anim: {
        enable: false,
        speed: 40,
        size_min: 0.1,
        sync: false
      }
    },
    line_linked: {
      enable: true,
      distance: 150,
      color: "#ffffff",
      opacity: 0.4,
      width: 1
    },
    move: {
      enable: true,
      speed: 3,
      direction: "none",
      random: false,
      straight: false,
      out_mode: "out",
      bounce: false,
      attract: {
        enable: false,
        rotateX: 600,
        rotateY: 1200
      }
    }
  },
  interactivity: {
    detect_on: "canvas",
    events: {
      onhover: {
        enable: false,
        mode: "repulse"
      },
      onclick: {
        enable: false,
        mode: "push"
      },
      resize: true
    },
    modes: {
      grab: {
        distance: 400,
        line_linked: {
          opacity: 1
        }
      },
      bubble: {
        distance: 400,
        size: 40,
        duration: 2,
        opacity: 8,
        speed: 3
      },
      repulse: {
        distance: 200,
        duration: 0.4
      },
      push: {
        particles_nb: 4
      },
      remove: {
        particles_nb: 2
      }
    }
  },
  retina_detect: true
};
export default particlesConfig;

This is my background component

import React from 'react';
import Particles from "react-tsparticles";
import particlesConfig from '../config/particles-config.js';

const particleBackground = () => {
  return (
    <Particles options={particlesConfig} height="50vh" width='50vw'/>
  )
}

export default particleBackground

And this is my App component

import React from "react";
import ParticleBackground from "./components/ParticleBackground";
import "./App.css"
const App = () => {
  return (
  <div className="App">
    <ParticleBackground/>
    <div className="particlesheader">
      <h1>Particle.JS</h1>
    </div>
  </div>
  );
};

export default App;

Hope you guys can help me out! Thanks!

How to draw a parabola using JavaScript

I have a code sample which i need to edit in order to draw a parabola
using only one line of code at the place marked
can any one advise ?

<html>
  <body>
  <canvas id="myCanvas" width="300" height="150"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var ctx = canvas.getContext('2d');
      ctx.beginPath();
      ctx.moveTo(0,0);
      for(var i=0;i<300;i++)
      {
          //i need to put one line of code here
      }
      ctx.stroke();
    </script>
 </body>
</html>

Next.js renders element twice

On the first image you can see next.js rendered this element twice

I used tables and thought that it is because of them but then I tried to remove tables and put jut and it still renders twice so I don’t know what it can be.

Next.js does not renders only that element but the first from this object

const Sections = {
  1: Locations,
  0: Departments, // here it will render this one twice
  2: Managers,
  3: JobTitles,
};

Maybe it has something to do with useState and my statemanagment in this code below

Component that renders twice.

const Locations = () => {
  return <div>hdjsad</div>;
};

enter image description here

enter image description here

// Tab Sections
import Locations from ''
import Departments from ''
import Managers from ''
import JobTitles from ''

import Icons from "../../Icons";
import TabItem from "./TabItem";

const tabs_text = ["Locations", "Departments", "Managers", "Job Titles"];

const Sections = {
  0: Locations, // THIS IS THE COMPONENT WHICH RENDERS TWICE
  1: Departments,
  2: Managers,
  3: JobTitles,
};

const SettingsTab = () => {
  const [active, setActive] = useState<number>(0);

  const select = useCallback((id: number) => {
    return () => setActive(id);
  }, []);

  const ActiveSection = useMemo(() => Sections[active], [active]);

  return (
    <section className={"mb-[24px]"}>
      <header
        className={"w-full flex items-center mb-[34px] pl-[24px] pr-[12px]"}
      >
        <div className={"flex space-x-[8px] !mb-0 overflow-x-scroll"}>
          {tabs_text.map((tab_text, i) => {
            return (
              <div onClick={select(i)} key={i}>
                <TabItem active={+active === i}>{tab_text}</TabItem>
              </div>
             
            );
          })}
        </div>

        <ImportLocationsAndFilter />
      </header>

      <ActiveSection />
      
    </section>
  );
};

APP.js

import { AppProps } from "next/app";

import "antd/dist/antd.css";

import "../styles/global.css";

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default MyApp;

Is there a way we can modify manifest.json generated in dev-server mode

I am using webpack-manifest-plugin plugin to generate a manifest.json file.
After that i have another plugin that runs after the complete build is done.
There I want to modify the manifest.json.Now this works fine with prod build(we are doing writeFileSync to update).

But in the dev-server build manifest.json does not get updated(as it not present in the filesystem it is in memory).
I want to update manifest.json after the complete build is done in dev-server-mode.
In dev-server mode build will not use the local file system it will in memory.

compiler.hooks.done.tap('After Compilation', (stats) => {
     // some code to update the manifest.json
})

Please let me know any way to access manifest.json post build and update in dev-server.
I tried afterEmit of webpack-manifest-plugin but I want it after the entire build is done.

Extjs 3.4.1 – how to hide a grid column when a specific radio button is clicked

Good day, I’m using Ext.js 3.4.1. I don’t have any code written yet but I’m trying to figure out in my mind the code on how to hide a blank column in the grid when I click on a radio button named “Hide blank columns”.

Radio button example: https://cdn.sencha.com/ext/gpl/3.4.1.1/examples/form/check-radio.html
column Grid example https://cdn.sencha.com/ext/gpl/3.4.1.1/examples/grid/array-grid.html

Can someone provide any snippets for this version of ext.js 3.4.1 that does the above?

Filepond upload button not letting users select images from mobile devices only letting them capture new photos

I’m using the vue-filepond library to setup image uploads.

I’m using these versions:

"filepond": "^4.30.3",
"filepond-plugin-file-validate-type": "^1.2.6",
"filepond-plugin-image-preview": "^4.6.10",
"vue-filepond": "^7.0.2",

This is my code:

  // Import Vue FilePond
  import vueFilePond from 'vue-filepond'

  // Import FilePond styles
  import 'filepond/dist/filepond.min.css'

  // Import FilePond plugins
  // Please note that you need to install these plugins separately

  // Import image preview plugin styles
  import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css'

  // Import image preview and file type validation plugins
  import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type'
  import FilePondPluginImagePreview from 'filepond-plugin-image-preview'

  // Create component
  const FilePond = vueFilePond(
          FilePondPluginFileValidateType,
          FilePondPluginImagePreview
  );

export default {
  components: {
    BreezeAuthenticatedLayout,
    BreezeButton,
    BreezeInput,
    BreezeLabel,
    Head,
    FilePond,
  },
}

Template:

<file-pond
    name="image_url"
    ref="pond"
    label-idle="Drop files here or <span class='filepond--label-action'>Browse</span>"
    :allow-multiple="false"
    accepted-file-types="image/jpeg, image/png"
    v-bind:files="myFiles"
/>

It works great on PC but when I try it from android devices it’s not letting me choose any photos, goes straight to camera capture.

How to change every number of an HTML input form into a subscript while typing? [duplicate]

I would like to create an HTML input form that converts every typed numerical value into a subscript. The numerical value that is typed into the input form, should immediately appear as a subscript while typing.

I am making a molar mass calculator for chemical formulas and it would be nice to show the correct form of a chemical formula. Users could, for example, type O2 into the input form and it should appear as O₂.

I have tried the following:

JavaScript:

const inputFormula = document.getElementById("input-formula");

inputFormula.addEventListener("input", function () {
     inputFormula.value = inputFormula.value.replace(/(d+)/g, "<sub>$1</sub>");
    });

On change of the input field, the JavaScript code will convert every number into a subscript, at least that was the idea, but it doesn’t work.

HTML:

<input type="text" id="input-formula" placeholder="formula" required>

However, when typing a number into the input field, the numbers are replaced with <*sub>”number”</*sub>, while I would like it to be replaced with the number displayed as subscript. Is this possible in HTML?

I added the * to prevent the sub tag from functioning as code

Any suggestions are welcome!! Thanks in advance!

How to sort `divs` based on user’s number of clicks using JS?

I’m using a script that counts how many times the user clicks each link and sort their order based on that number…

It works fine as is, however it doesn’t work if the <a> tags is nested inside a div. It’s ignoring the divs and the content/image/icon inside, while showing only the links..

How to change it so that it will show and reorder the entire div instead of just the link?

Please see what I have so far:

function updateClicks(ele) {
  const storage = window.localStorage.getItem(ele.innerHTML + " clicks");
  if (storage === null) {
    window.localStorage.setItem(ele.innerHTML + " clicks", "1");
  } else {
    var clicks = parseInt(window.localStorage.getItem(ele.innerHTML + " clicks")) + 1;
    localStorage.removeItem(ele.innerHTML + " clicks");
    window.localStorage.setItem(ele.innerHTML + " clicks", clicks);
  }
}

function orderItems() {
  var order = [];
  var href = [];
  var links = document.getElementById("links-list");
  var link = links.getElementsByTagName("a");
  for (i = 0; i < link.length; i++) {
    href.push(link[i].href);
  }
  links = links.innerHTML.split("</a>");
  document.getElementById("links-list").innerHTML = "";
  for (i = 0; i < links.length - 1; i++) {
    var lastChar = links[i].charAt(links[i].length - 1);
    var clicks = parseInt(window.localStorage.getItem(lastChar + " clicks"));
    if (isNaN(clicks)) {
      clicks = 0;
    }

    order.push([lastChar, clicks, href[i]]);
  }
  order.sort(function(a, b) {
    return a[1] - b[1]
  });
  order.reverse();
  console.log(order)
  for (i = 0; i < order.length; i++) {
    document.getElementById("links-list").innerHTML += "<a href='" + order[i][2] + "'  onclick='updateClicks(this)'>" + order[i][0] + "</a>";
  }
}
.link-container {
  display: inline-block;
}

.link-container a {
  padding: 10px;
  background-color: #c0c0c0;
}

.link-img {
  width: 16px;
  height: 16px;
}
<body onload="orderItems();">

<div id="links-list">
  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/6ZpMxiG.png" />
    <a href="#" onclick="updateClicks(this)">A</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/sFUFOyO.png" />
    <a href="#" onclick="updateClicks(this)">B</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/M5a2gh8.png" />
    <a href="#" onclick="updateClicks(this)">C</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/mbrEuvR.png" />
    <a href="#" onclick="updateClicks(this)">D</a>
  </div>

</div>
</body>

I’m still trying to learn JS and I need this feature for a project I’m building.. Thank you in advance for any help.

How to calculate and distribute the result on html?

I have two values on my html: “Money” and “Time”, and those values come from Session Storage, depending on what the person filled previously on another html page.
So lets say the person filled that they need to pay $100 in 2 days.

What i’m trying to do, is to create a list, showing the number of payments, with the amount to be paid in each payment. Like the example below

MONEY: $100 /
TIME: 2 Days

RESULT:

  • $50
  • $50

    So if the person has 5 days, instead of 2, it would appear as:

  • $20
  • $20
  • $20
  • $20
  • $20

    What i have so far is:

    HTML

    <p id="money-value"></p>
    <p id="time-value"></p>
    
    <div id="payments"></div>
    
    <script>
    
    const displayMoney = document.getElementById("money-value");
    const storedMoney = sessionStorage.getItem("Money");
    window.addEventListener("load", () => {
    displayMoney.innerHTML =  "Money: " + storedMoney
    });
    
    const displayTime = document.getElementById("time-value");
    const storedTime = sessionStorage.getItem("Time");
    window.addEventListener("load", () => {
    displayTime.innerHTML =  "Time: " + storedTime
    });
    
    </script>
    

    What i’m trying to do here, is to use Javascript to create a list element, inside the <div id="payments> that would not only calculate the amount to be paid in each payment, but also that the number of “topics” (payments) would increase, according to the number of “time” the person has (Just like the example i gave).