Progressive web app stuck in portrait mode despite auto-rotate being enabled on phone

I’m developing a website which I’ve also created a Progressive Web App (PWA) Android app for by using https://pwabuilder.com

In my manifest.json file I initially had the orientation property set to any, but with this, the installed PWA on my phone would auto-rotate, despite “Auto Rotate” being disabled on my phone. No good.

Description of manifest.json property values

So I tried setting the orientation property in my manifest.json to natural instead, and I also tried just deleting the property entirely, but in both cases now all rotation was disabled. That is, regardless of whether or not I enable or disable “Auto Rotate” on my phone, the installed app is stuck in portrait mode.

None of this is a problem on the website version of the site of course. If I just navigate to the page in Chrome, it works fine. That is, if I disable “Auto Rotate” on my phone, then the site doesn’t rotate, but if I enable it, then it rotates when I physically rotate my phone. I just want my PWA to mimic this behavior, but I’m not exactly sure how.

What value should I be setting the orientation property to in my manifest.json in order to mimic the default behavior of the website?

I can’t connect mongodb db with my node.js code

const express = require('express');
const mongoose = require('mongoose');
const app = express()

//declare variables

const uri = 'mongodb://localhost:27017/Account'

//uri to local mongo db

async function run () {
    try {
        await mongoose.connect(uri);
        console.log('connected');
}
    catch(error){
        console.log(error);
}
}

run();

//a simple function to try

app.listen(3000, ()=>{
    console.log('listen!')
})

//doesn’t work!! why??

Toastify-js library for login attempts

I need to show a toast notification for a user’s sucessful and unsuccessful login attempts using the toastify-js library. There is existing functionality in a file that handles authentication HTTP requests and actions, that shows alerts instead of toast notifications for these login attempts.

When I try to implement the toast notifications using the library within the existing funcitonality it either doesn’t show or has client connection errors.

      if (axiosResponse.status === 200) {
        console.log('Status Code: ' + axiosResponse.status + ' ' + axiosResponse.statusText)
        console.log("Login response: ", axiosResponse.data);
        
        await client.set("JWT", axiosResponse.data.tkn, (err, res)=> {
          if (err) {
            console.log("Set JWT Token error: ", err)
          } else {
            console.log("Set JWT successfully: ", res)
          }
        })
        await client.set("Roles", axiosResponse.data.roles.toString(), (err, res)=> {
          if (err) {
            console.log("Set User Roles Token error: ", err)
          } else {
            console.log("Set User roles successfully: ", res)
          }
        })
        res.status(200).send(
        `<script> 
          //alert("Login Successfully");
          window.location.href = "/welcome"
        </script>`);

This is a part of the existing login error handling. Is this the best place to implement the notifications for a successful login?

Django Python+Ajax : how to update variable from frontend to back end? My ajax function isn’t working

When the user submits this form I want to save the rgb color code as a variable to be stored on the back end (using django), so whenever the card is loaded (the colour picked on this page) will be loaded. I asked GPT, which suggested using ajax (I’ve never used it before).

This is a snippet from my js :

function updateSetColor(color) {
            console.log(color);
                $.ajax({
                    type: "POST",
                    url: "/Flashcard/",
                    beforeSend: function(xhr, settings) {
                        xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
                    },
                    data: { color: color },
                    error: function(error) {
                        console.log("Error updating color");
                    },
                    cache: false,
                });
        }

This is a snippet from my view that uses the color variable sent from the data :

def flashcard(request):
    form = Flashcard_verif(request.POST)

    if request.method == "POST" and form.is_valid() and request.accepts('main/Flashcard.html'):
        print(request.POST)
        color = request.POST.get("color")  # Get the color from the AJAX request
        print(color)

As you can see I’ve got the console to output the color picked by the user and on the backend I’ve got the server to output the color that should’ve been recieved. The output from the console is correct but the output from the server is ‘None’. I suspect its due to the ajax function. Any help would be appreciated or new ways of achieving what I want to.

How to convert an array of objects into an array of arrays using Ramda

I would like to transform this:

[
  { a: 2000, b: 4000 },
  { a: 8000, b: 5000 },
  { a: 6000, b: 1000 }
];

Into this:

[
  [ 2000, 8000, 6000 ],
  [ 4000, 5000, 1000 ]
];

Using Ramda.

I can do this using just R.reduce, but I’m wondering if there’s a way that uses as little custom code as possible and instead makes full use of the functions Ramda provides.

One more caveat; the solution can’t assume that the keys in the objects are known. They will always be consistent between objects, but may change every time this function is run. For example, the next run of the code could be:

Input:

[
  { c: 1000, d: 4000, e: 7000 },
  { c: 2000, d: 5000, e: 8000 },
  { c: 3000, d: 6000, e: 9000 }
];

Result:

[
  [ 1000, 2000, 3000 ],
  [ 4000, 5000, 6000 ],
  [ 7000, 8000, 9000 ],
];

Running asnyc function synchronously

I’m pretty new to JS. I’m using a third-party library that has an async callback. The problem is that I need to run through the function in its entirety before processing the next callback. I’m using an upload protocol called tus.io and need to process one upload at a time.

async onUploadCreate(req, res, uploadMetadata) {

    /* I need to check the metadata is valid by using an internal js file */
    //...

    /* Then I need to check the user is logged in by calling a third-party endpoint using axios*/
    //...

    /* Then I check the Mongo db for existing uploadId
    //...
        // if it's not there, create some entries in another db and add the uploadId to mongo
        //If it is there, get some IDs in mongo, which I append to another db
}

As you can see, I need to do a fair bit. I do this because in tus, there is no concept of an upload session; each file comes in an independent upload. I’ve been testing it by uploading one file at a time. When i use multiple files it’s all over the place.

Is there a way I can achieve this in JavaScript? I know this could have a performance impact, so I’m open to suggestions on how else I could achieve this.

Creating Pages deployment failed

upon uploading my files into repository in GitHub, no link of the website in pages section on the settings created and the repository shows error in the deployment to GitHub pages ( the 3rd step of processing ). can anyone help me?

I have deleted the repository and recreated another one with the same files, but nothing changed, the error still happening.

My animated Items disappear when on mobile

I had this problem before, I thought it was because the images were lazy loaded but now its doing it with text, I’m using tailwind with NextJS this is my code

coinBanner.tsx

<div className="w-max flex gap-8 relative bg-gray-900 text-white h-12 items-center ">
      <div className="flex gap-8  animate-sliding ">
        <p>Trending</p>
        {store.coins.map((item: coinType) => {
          return (
            <p className="overflow-visible" key={item.symbol}>
              {item.symbol}
              <span className="pl-1">${item.priceUsd}</span>
            </p>
          );
        })}
      </div>
      <div className="flex gap-8  animate-sliding ">
        <p>Trending</p>
        {store.coins.map((item: coinType) => {
          return (
            <p className="overflow-visible" key={item.symbol}>
              {item.symbol}
              <span className="pl-1">${item.priceUsd}</span>
            </p>
          );
        })}
      </div>
    </div>

Tailwind.config.ts

const config: Config = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      backgroundImage: {
        "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
        "gradient-conic":
          "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
      },
      keyframes: {
        slide: {
          "0%": { transform: "translateX(-100%)" },
          "100%": { transform: "translateX(0%)" },
        },
      },
      animation: {
        sliding: "slide 15s linear infinite",
      },
    },
  },
  plugins: [],
};

I want the images to infinitely slide to the left

How do I successfully port complex components with module federation and solid-js?

I have been trying to learn Solid-js for a couple weeks now, and thought I’d try to work through a micro-frontend tutorial and settled on this Jack Herrington example: https://www.youtube.com/watch?v=lKKsjpH09dU

He’s recently updated the final edition so it works on download and you can examine the working parts, but I’ve been using the Solid-js/Tailwind options for everything but the server. I’m stuck at the point of bringing the cart:Login/MiniCart to the home:Header (about 1:24:xx in the video).

I get an error about a null reference to “name”, which actually refers to the component name in the dev bundle (generated by WP/MF). I assume the issue is with the way I’ve found that works to create the Login/MiniCart components, rather than how I’m bringing it in (but I’ll post both, just in case).

I assume the issue is with persistence of webhooks, but as I’m new to both Module Federation and SolidJS, I’m unsure.

Here is my Login.jsx:

import { createSignal } from 'solid-js';

import { login, useLoggedIn } from './cart';

export const Login = () => {
    const loggedIn = useLoggedIn(),
        [showLogin, setShowLogin] = createSignal(false),
        [user, setUser] = createSignal('sally'),
        [pw, setPw] = createSignal('123');

    return (
        <>
            {!loggedIn() && (
                <span onClick={() => setShowLogin(!showLogin())} id='showlogin_span'>
                    <i className='ri-fingerprint-line text-2xl' id='showlogin'></i>
                </span>
            )}
            {showLogin() && (
                <div
                    className='absolute p-5 border-4 border-blue-800 bg-white rounded-xl text-black'
                    style={{
                        width: 300,
                        top: '2rem',
                        left: -250
                    }}>
                    <input
                        type='text'
                        placeholder='User Name'
                        value={user()}
                        onChange={(evt) => setUser(evt.target.value)}
                        className='border text-sm border-gray-400 p-2 rounded-md w-full'
                    />
                    <input
                        type='password'
                        value={pw()}
                        onChange={(evt) => setPw(evt.target.value)}
                        className='border text-sm border-gray-400 p-2 rounded-md w-full mt-3'
                    />
                    <button
                        className='bg-green-900 text-white py-2 px-5 rounded-md text-sm mt-5'
                        onClick={() => {
                            login(user(), pw());
                            setShowLogin(!useLoggedIn);
                        }}
                        id='loginbtn'>
                        Login
                    </button>
                </div>
            )}
        </>
    );
};

Here is my Header.jsx:

import Login from 'cart/Login';
// import MiniCart from 'cart/MiniCart';

const Header = (props) => {
    return (
        <>
            <div className='p-5 bg-blue-900 text-blue-400 text-3xl font-bold'>
                <div className='flex'>
                    <div className='flex-grow'>Digital Trading Cards | {props.name}</div>
                    <div className='flex-end'>
                        <Login />
                        {/* <MiniCart /> */}
                    </div>
                </div>
            </div>
        </>
    );
};

export default Header;

How to get the context of an iframe (google payframe) using puppeteer

So basically I’m testing the adyen drop-in googlepay integration, for this I need to login, follow a link to the page with the gpay button, click it and then in the appearing popup I need to click the pay button.

I managed to accomplish the first steps and am lacking the last one which is to click the pay button.

Here’s my toy script:

const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');

puppeteer.use(StealthPlugin());

const dotenv = require('dotenv');

dotenv.config();

const clickGooglePayButton = async () => {};

const loginFromPage = async (browser) => {
  const page = await browser.newPage();
  await page.goto(process.env.LOGIN_LINK);

  const email = 'input[type="email"]';
  const password = 'input[type="password"]';

  await page.waitForSelector(email);
  await page.type(email, process.env.EMAIL);
  await page.keyboard.press('Enter');
  await page.waitForNavigation();

  await page.waitForSelector(password);
  await page.type(password, process.env.PASS);
  await page.keyboard.press('Enter');

  await page.waitForNavigation();

  return page;
}

const run = async () => {
  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 50,
    args: [
      '--disable-web-security',
      '--disable-features=IsolateOrigins,site-per-process',
    ],
  });

  await loginFromPage(browser);
  const gpayTabRef = await browser.newPage();
  await gpayTabRef.goto(process.env.GPAY_LINK);

  const gpayButton = await gpayTabRef.waitForSelector('div.gpay-card-info-container-fill button');
  console.log(gpayButton);

  await gpayButton.click();
  const openPages = await browser.pages();
  console.log(openPages);

  const targets = browser.targets();

  const targetFrame = await browser.waitForTarget(target => target.url().includes('https://pay.google.com/gp/p/ui/payframe?origin'));
  console.log('returning the target type');
  console.log(targetFrame.type());
  console.log(await targetFrame.page());

}

run();

I tried playing around with targets, but looks like this pay frame is no page, cos the page method on this target simply resolves to null.

I’ve also tried playing around with frames:

  const frames = await gpayTabRef.frames();
  console.log('logging frames...');
  console.log(frames);
  const content = await frames[frames.length - 1].content();

but I’m not getting the content of that pay popup with the pay button…I feel that the solution is somewhere near but would very much appreciate some help.

How can I set an Office Script autofill command to dynamically autofill to the last row?

I am trying to set an Excel script to autofill this column down to the final row of data, and no further. Different tables I am running the script on have different numbers of rows, so the current script with the hardcoded number of rows isn’t very useful. I’m looking to get the script to autofill dynamically, regardless of the number of rows in the table it is operating on.

function main(workbook: ExcelScript.Workbook) { let selectedSheet = workbook.getActiveWorksheet(); selectedSheet.getRange("B2").autoFill("B2:B237", ExcelScript.AutoFillType.fillDefault); }

I tried just hardcoding the .autofill() to B2:B2000, but that filled blank rows after the last row, which I do not want. Then I tried B:B, which broke the script. Any feedback would be greatly appreciated. Thanks!

Js extract information from a json

I have the following json that is quite complex and detailed.

I need to extrapolate information (text) from the json only if the resource-id contains the following text "com.shazam.android:id/" and if it contains the following props (["title", "subtitle", "datetime"]).

If last element does not contain a datetime then resorceIdFinal is not inserted.

Below is an example json I want to get.

Here you can find the json I use, I couldn’t insert it here due to character space.

Link: https://pastebin.com/raw/hFLmP2T8

const check = (obj, keys) => !keys.some((el) => !obj.hasOwnProperty(el));

const isObjectEmpty = (objectName) => {
  return (
    objectName &&
    Object.keys(objectName).length === 0 &&
    objectName.constructor === Object
  );
};

const getChildren = (el, replaceText, props, resorceIdFinal) => {
  var arr = [];

  el.forEach((el) => {
    let resorceId = getResorceId(el.attributes, replaceText, props, resorceIdFinal);
    if(!isObjectEmpty(resorceId)) arr.push(resorceId);   
    //console.log(arr);
    getChildren(el.children, replaceText, props, resorceIdFinal);
  });
  
  return arr;
};


const getResorceId = (el, replaceText, props, resorceIdFinal) => {
  var o = {};
  if (el["resource-id"] !== undefined) {
    var resorceId = el["resource-id"].replace(replaceText, "");
    if (props.includes(resorceId)) {
      o = { [resorceId]: el.text };
    }
  }
  return o;
};

function readPro(json, replaceText, props, filterA, resorceIdFinal) {
  var arr = [];

  json.forEach((el) => {
    arr.push(getChildren(el.children, replaceText, props, resorceIdFinal));
  });
  
  console.log(arr)

  filtered = arr.filter(
    ((s) => (o) =>
      ((k) => !s.has(k) && s.add(k))(filterA.map((k) => o[k]).join("|")))(
        new Set()
      )
  );

  return filtered;
}


var res = readPro(
  a.children,
  "com.shazam.android:id/",
  ["title", "subtitle", "datetime"],
  ["title", "subtitle"],
  "datetime"
);

console.log(res);

Json result I would like to get:

[
   {
        "title": "Believe",
        "subtitle": "Chuther",
        "datetime": "12 giu, 16:42"
   },
   {
        "title": "시작 (Inst.)"
        "subtitle": "Gaho"
        "datetime": "12 giu, 16:42"
   },
   {
        "title": "Give It Up"
        "subtitle": "KC and the Sunshine Band"
        "datetime": "12 giu, 16:41"
   },
   {
        "title": "GRAVITY"
        "subtitle": "Jong Ho"
        "datetime": "12 giu, 16:41"
    }
]

Can you give me a hand?

How can I Inject JavaScript code into a window object

I am trying to make a JavaScript injector for any website so you don’t have to rely on bookmarklets and such. Every time I run my code, it tells me that my newWin.window.location.href = 'about:blank', and it tells me that my newWin.document.body.parentElement.innerHTML = '<head><body></body></head>'

Note: I am using alert(); instead of console.log(); beacuse DevTools is blocked

My Code:


let newWin = window.open('https://my_example.com');
try{
    var js_code = newWin.document.createElement('script');
    js_code.setAttribute('source.js',''); //Note that source.js has "alert('Hello World')" in it
    document.head.appendChild(js_code);
    alert(newWin.document.body.parentElement.innerHTML)    

} catch (error){
    alert(error);
}

I tried to set the window location manually but it stayed the same:

newWin.window.location.href = "https://my_example.com"

but to no avail.

I also tried to use:

document.write(newWin.document.body.parentElement.innerHTML + '<script>alert("Hello World")</script>

Issue with calling a method from another file inside of a function in a index.js file

So I’m trying to call a method which would close my forms, I’m trying to call this inside of my index.js file, but I can’t seem to make it work, can someone help me find the solution for this problem. Here is a link to my repo https://github.com/XDRO/se_project_aroundtheus, and a screenshot of the code.code inside of popup.js and index.js

So I’ve tried to call this method similar to my other methods, and I’ve conole.log() the this._popupClose to make sure that I’m selecting the right element, to apply the event listeners to as well as the close method to, I’ve looked at a few different StackOverflow answers, but none of them really apply to my situation, everything I’ve tried has either resulted in an error or resulted in nothing happening at all, I’m pretty new to coding so the answer might be obvious, but I would greatly appreciate any help provided.