Salesforce Lightning Web Component to Retrieve Values from Device Storage

I have a Lightning Web Component for use in the Salesforce Mobile App. The LWC is an app that has been built out and is working well, but I wanted to add a Settings screen for the users. To do so, I’ve created a few checkboxes I want the user to be able to check or uncheck (they default to checked). These checkbox values are stored on the user’s device using localStorage.setItem(). I am able to store the data on the device and retrieve it when the app launches. I then place the values from the device storage into variables in the LWC (showModel for example). I have been able to verify that the value of the showModel variable is being correctly set based on the data in the device’s memory when the app launches. However, the lightning-input checkbox is not being rendered unchecked if the value of the showModel variable is false. That is, if a user unchecks the checkbox, closes the app, and then relaunches the app, the checkbox appears checked when the app loads even though showModel is being set to false. If anyone knows how I might be able to fix this, help would be greatly appreciated.

Here is the html for the Settings page (showing only one checkbox at the moment):

<lightning-card lwc:if={showSettings}>
        <div class="custom-title" slot="title">
            <lightning-button-icon icon-name="utility:back" variant="bare" name="settingsBack" alternative-text="Back" title="Back" label="Back" onclick={handleSettingsBack} size="large"></lightning-button-icon> Custom Settings
        </div>
        
        <div class="slds-m-around_medium">
            <div class= "custom-title slds-text-title_caps slds-text-color_weak slds-p-top_large">Show Fields</div>
            <div class="slds-text-body_regular slds-m-top_small slds-m-bottom_medium">Select which fields to see:</div>
        </div>
        <div class="slds-m-around_medium">
            <lightning-layout class="slds-m-top_medium">
                <lightning-layout-item flexibility="auto">
                    <lightning-input type="checkbox" label="Model Name" name="showModel" value={showModel} checked={showModel} onchange={handleShowModelChange}></lightning-input>
                </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>

And the relevant JS:

export default class AssetInput extends LightningElement{

@track showModel = '';

connectedCallback(){
    //A few other things get done first, and then...
        this.loadSettings();
    }

loadSettings(){
        if(localStorage.getItem('showModel') !== null){
        this.showModel = localStorage.getItem('showModel');
        //I placed an alert for a toast message here to verify this runs, and saw the toast. 
        //At one point I also made a button I could press to show the value of showModel and when pressing the button immediately after the app loaded, it would display "false" but the checkbox would remain checked
    }else{
        localStorage.setItem('showModel', true);  //this is intended to set the value to true the first time the app runs
    }
    }


handleShowModelChange(event){
        localStorage.setItem('showModel', event.target.checked);
        this.showModel = event.target.checked;
    }

}

It might also be worth mentioning that I have some settings working. I’m allowing the user to set default values for a couple fields, so I’m storing strings for those fields instead of boolean true/false values like for these checkboxes. The strings are all loaded properly and displayed in their lightning-inputs as expected. I’m doing the same thing to load those values as I am for these, but these checkboxes aren’t cooperating.

To summarize: when the checkbox is interacted with while the app is running, everything works as expected. However, if the checkbox is unchecked and the app is reloaded, the checkbox is always rendered checked instead of unchecked.

Why is my camera capabilities not showing zoom using getUserMedia()?

When I read my camera capabilities using getUserMedia() in JavaScript / HTML, the property zoom always returns null. But my Android phone has zoom functionality on the camera and other apps that use the camera.

I’ve read that it might appear after waiting 5 seconds, but it still return null. I am using QuaggaJS to scan barcodes.

Does anyone know why this happens?

checkCapabilities: function() {
    var track = Quagga.CameraAccess.getActiveTrack();
    var capabilities = {};
    if (typeof track.getCapabilities === 'function') {
        capabilities = track.getCapabilities();
    }

    // Apply max zoom?
    console.log('capabilities.zoom:', capabilities.zoom)

    if( capabilities.zoom )
    {
        console.log('capabilities.zoom.max:', capabilities.zoom.max)

        track.applyConstraints({ advanced: [{zoom: capabilities.zoom.max}]}).catch(e => 
        console.log(e));
    }
}

Output from the 3 boxes the same format as the premade boxes

Im trying to make it so where whatever you type into those 3 boxes gets outputted onto the screen with the same format as the other boxes you already see.

I am trying to use a cloneNode method to duplicate the template of the other boxes and store it in the variable but I can’t seem to find out what to do. So the first input label get set at the top of a box, the 2nd label into the middle, and the third the bottom of the box just like the boxes you already see on the screen.

`https://codepen.io/Jackson-Grove/pen/LYvzoBg`

How to save a block with overflow-y in html2pdf.js

I have a block.

<div  class="container"> 
<div  class="words-wrapper"> 
content
</div>
</div>

and such styles

.words-wrapper {
    max-height: 750px;
    overflow-y: auto;
}

My settings for html2pdf

const element = document.querySelector('.container')
    const opt = {
                margin: 0.5,
                filename: `${pageTitle.value}.pdf`,
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
                pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
    }

Also I add settings for printing

@media print {
    .words-wrapper {
        max-height: none !important;
        overflow-y: visible !important;
    }
}

Therefore, a block with a scroll.
When printing through a browser, all pages are displayed.
But through html2pdf, it only generates the visible part of the content.

I tried adding styles to this block before forming, but it didn’t help.

const wordsWrapper = document.querySelector('.words-wrapper')
        wordsWrapper.style.maxHeight = 'none!important'
        wordsWrapper.style.overflowY = 'visible!important'

Why is .then not working on my method chain of promises? [closed]

I am working on promises on JS, and wanted to method my chain my 3 three promises using .then. I am receiving the error: Uncaught TypeError: Cannot read properties of undefined (reading ‘then’)
at :1:10

function walkDog() {
  const dogWalked = new Promise((resolve, reject) => {
    setTimeout(() => {
      const dogWalked = true;

      if (dogWalked) {
        resolve('You walked the dog');
      } else {
        reject("You did not walk the dog");
      }
    }, 1500);
  });
}

function cleanKitchen() {
  const kitchenCleaned = new Promise((resolve, reject) => {
    setTimeout(() => {
      const kitchenCleaned = true;

      if (kitchenCleaned) {
        resolve("You cleaned the kitchen");
      } else {
        reject("You did not clean the kitchen");
      }
    }, 5000);
  });
}

function takeOutTrash() {
  const trashTakenOut = new Promise((resolve, reject) => {
    setTimeout(() => {
      const trashTakenOut = true;

      if (trashTakenOut) {
        resolve("You took out the trash");
      } else {
        reject("You did not take out the trash");
      }
    }, 500);
  });
}

// Function chaining
walkDog()
  .then((value) => {
    console.log(value);
    return cleanKitchen();
  })
  .then((value) => {
    console.log(value);
    return takeOutTrash();
  })
  .then((value) => {
    console.log(value);
    return console.log("You did all your chores. Well done :)");
  });

I was expecting to receive the following text:

You walked the dog
delay….
You cleaned the kitchen
delay…
You took out the trash
You did all your chores. Well done 🙂

Instead, I received an error on my console:

1 Uncaught TypeError: Cannot read properties of undefined (reading ‘then’)
at :1:10

Hamburger drop down menu not working on mobile version of my website

A developer built a very broken website from the SEO standpoint so I needed to tweak it a lot with different htaccess rules.

I got everything working properly, the website works well offline but after hours of tweaking and thinking it’s a JS issue, I finally understood that it has most likely to do with my htaccess rules. I need these redirects to happen, but also need the menu to work on mobile. Can someone help me out with this? Other elements are working well so that’s why I think it’s this htaccess issue. Thanks a ton!

Here’s my htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.abc.gr [NC]
RewriteRule ^(.*)$ https://abc.gr/$1 [L,R=301]

RewriteRule ^index$ https://abc.gr [L,R=301]

RewriteRule ^(.+).html$ https://abc.gr/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ https://abc.gr%1 [NE,R=301,L]

RewriteCond %{HTTP_HOST} ^abc.gr$ [OR]
RewriteCond %{HTTP_HOST} ^www.abc.gr$
RewriteRule ^go$ "https://record.abc.com/_/1/" [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)/?$ $1.html [L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index.html\ HTTP/
RewriteRule ^index.html$ / [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index.htm\ HTTP/
RewriteRule ^index.htm$ / [R=301,L]

I first thought that it might be an issue that my logo container width was too large, edited that. Changed nothing. Then I thought it’s something in the JS file, but tried everything and didn’t work. I’ve tweaked almost everything but to no avail.

fs.write() vs fs.writeFile() vs fs.appendFile()

What is the difference between fs.write(), fs.writeFile() and fs.appendFile()?

I’m having some trouble understanding what exactly the difference between these 3 methods is because to me, they ultimately look the same, or rather like shortcuts to one another.

From the base description of fs.write() and fs.writeFile() they seem the same, noticeable differences are the number of parameters, fs.writeFile() has more. But then in the description of fs.writeFile() it says

Similarly to fs.readFile – fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it.

So it’s just a faster and automatic way to call multiple fs.write()? Which brings us to fs.appendFile(), because that just seems like a shortcut for fs.writeFile() with the a flag set. The only difference I can see are the default set flags and the number of types you can use for the data.

Then there would also be fs.createWriteStream(), but that clearly differentiates itself
in several ways and has a different use case than the write() methods, like a logger that has to write fast and often, so I do get the difference there.

Need to create list, every li needs to be a link to a pdf page

so one client asked me if i could make a dropdown list on his website, the dropdown list is not a problem the problem is that every <li> needs to be a link to a different page of a PDF file.
The problem is that i don’t know if it’s an easy and achievable thing or if it’s possible because of my knowledge.
Another problem is that the website in question is a wordpress site and i know even less about wordpress, i’m trying to change the thinking of my boss about wordpress but i need an example of the working component, another problem is that i have little to no time to make it, but if i can have a working component maybe i can shift my boss mindset about free coding.

I tried to search for components and or WP plugins but didn’t find a way to make it

How to not override multiple transition properties

I have an element which can have different transitions on different events.

In the example below, the square becomes orange when you hover it, and become longer or larger if you toggle one of the checkboxes.
These transitions are not active when you remove the w-100 or h-100 class, or on mouseout.

The problem multiple events are active on the same time, the properties will be overridden.

I could set the transition-property on each case, but I imagine

What’s the best way to keep all these event active no matter the situation ?

#square {
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

#square:hover {
  background-color: orange;
  transition: background-color 500ms;
}

#toggleWidth:checked~#square {
  width: 100px;
  transition: width 500ms;
}

#toggleHeight:checked~#square {
  height: 100px;
  transition: height 500ms;
}
<input type="checkbox" id="toggleWidth" name="toggleWidth" />
<label for="toggleWidth">Toggle width</label>
<input type="checkbox" id="toggleHeight" name="toggleHeight" />
<label for="toggleHeight">Toggle height</label>
<br><br>
<div id="square"></div>

How to await rendering of visible DOM changes?

If we have some browser JS code that does a lot of computation, how to reliable yield to allow the browser do some rendering inbetween, eg. we want to display progress indicators? I tried awaiting requestAnimationFrame handler, but that – for at least in Chromium – does not always allow rendering to happen.

Example:

...compute...

statusElement.innerText = 'were almost done!';
await new Promise(resolve => window.requestAnimationFrame(resolve));

...compute...

does often, but not always show “were almost done” until the second computation is completed and the JS code exits.

So is there any canonical way to make sure this DOM change is visible before proceeding?

Display/hide a div based on the time

I’m currently building a website using Webflow. I need to display a div “We are open” or “We are closed” based on the time slots defined by my client, in order to inform website visitors whether they can call or not. However, it’s not working 100%. For example, at 4:20 PM, it already shows “We are closed” when it should still display “We are open”.

Here is the temporary link to the site: https://gaia-reunion.webflow.io/ The div in question is located at the bottom of the page here: https://gaia-reunion.webflow.io/#talk.

So far, I’ve tried this solution:

<script>
// Fonction pour afficher ou masquer les div en fonction de l'heure de l'île de la Réunion
function afficherDivSelonHeure() {
    var date = new Date();
    var options = {timeZone: 'Indian/Reunion'};
    var heureReunion = date.toLocaleTimeString('fr-FR', options); // Récupérer l'heure locale de l'île de la Réunion

    var heure = parseInt(heureReunion.split(':')[0]); // Récupérer seulement l'heure
    var minute = parseInt(heureReunion.split(':')[1]); // Récupérer seulement les minutes

    // Convertir l'heure de l'île de la Réunion en heure UTC pour faciliter la comparaison
    var heureUTC = (heure - 4) % 24; // UTC+4 pour l'île de la Réunion

    // Déterminer le jour de la semaine
    var jour = date.getDay();

    // Vérifier si c'est un jour ouvrable et si l'heure est dans les plages horaires spécifiées
    var plageHoraire1 = (heureUTC >= 8 && heureUTC < 12) || (heureUTC === 12 && minute === 0); // plage horaire du matin
    var plageHoraire2 = (heureUTC >= 13 && heureUTC < 17) || (heureUTC === 17 && minute === 0); // plage horaire de l'après-midi

    var jourOuvrable = false;

    // Déterminer si c'est un jour ouvrable en fonction du jour de la semaine et des plages horaires spécifiées
    switch (jour) {
        case 1: // Lundi
        case 2: // Mardi
        case 3: // Mercredi
        case 4: // Jeudi
            jourOuvrable = plageHoraire1 || plageHoraire2;
            break;
        case 5: // Vendredi
            jourOuvrable = (heureUTC >= 8 && heureUTC < 13) || (heureUTC === 13 && minute === 0); // plage horaire spéciale pour le vendredi
            break;
        default:
            jourOuvrable = false;
    }

    // Sélectionner les divs
    var divOpen = document.getElementById("div-open");
    var divClose = document.getElementById("div-close");

    // Afficher div-open si c'est un jour ouvrable et l'heure est dans les plages horaires spécifiées, sinon afficher div-close
    if (jourOuvrable) {
        divOpen.style.display = "block";
        divClose.style.display = "none";
    } else {
        divOpen.style.display = "none";
        divClose.style.display = "block";
    }
}

// Appeler la fonction une fois au chargement de la page pour afficher les divs correctement
afficherDivSelonHeure();

// Rafraîchir l'affichage toutes les minutes pour prendre en compte les changements d'heure
setInterval(afficherDivSelonHeure, 60000);

</script>

It seems to be working partially, as mentioned earlier. For example, at 4:20 PM, it already displays “We are closed” when it should still display “We are open”.

Trying to use javascript in my cefsharp browser

I’m trying to use bind my application with youtube video playing in cefsharp browser but it’s not working. I don’t get what is wrong with my code:

c#

private async void Music_Play_Pause_Button_Click(object sender, EventArgs e)
{
    try
    {
        //bring javascript method
        string script = "toggleVideoPlayback();";
        var response = await music_player.EvaluateScriptAsync(script);

        if (response.Success && response.Result != null)
        {
            bool isPlaying = Convert.ToBoolean(response.Result);
            MessageBox.Show($"Video playback toggled: {(isPlaying ? "Playing" : "Paused")}");
        }
        else
        {
            MessageBox.Show("Failed to toggle video playback.");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Error toggling video playback: {ex.Message}");
    }
}

javascript

function toggleVideoPlayback() {
    var videoElement = document.getElementById('player');
    if (videoElement) {
        if (videoElement.paused) {
            videoElement.play();
        } else {
            videoElement.pause(); 
        }
        return !videoElement.paused; 
    } else {
        return false; 
    }
}

javascript and cs file is in the same folder and the message that I set to check, which is “Failed to toggle video playback.” is the only thing that shows up. As you can see in my code, I expect when button is clicked, I want video to be paused or played

Can’t set a checkbox to checked in tinyMCE editor

Working on a project where we insert HTML inside a tinyMCE editor.
I have a requirement to be able to check/uncheck the required checkbox control.
If I place a break point on the editor click event it catches in the debugger and as you can see the checkbox is checked.But as soon as the event finished running the state of the checkbox goes back to unchecked.I have tried manually setting the value to checked inside the event.I have also tried stopping event propagation by using:

 e.preventDefault();
 e.stopPropagation();

But nothing seems to work and the checkbox always goes back to unchecked.Any tips from tinyMCE experts welcome

enter image description here

React app – unable to connect to Node server

The port number in the frontend is same as the backend’s; however, when I tried to make a post request from the frontend (i.e. sign up a user), I got the following response error:

   POST http://localhost:5173/users/sign-up net::ERR_ABORTED 404 (Not Found)

I tried to console.log the corresponding function that creates users in the backend, but seems like it’s not outputting anything

So far I’ve tried with a different port number on both sides and checked the browser’s Network tab but still no luck. The Network tab shows the same error I mentioned.

django Could not parse the remainder: ‘[0]’ from ‘carray[0]’

hi i receved the mistake above with this sutiuation

type here def check_url_exists(url_to_check):
    try:
        countArray= []
        # محاولة استرداد سجل بناءً على الرابط المعطى
        display_obj = Display.objects.get(url=url_to_check)
        for i in range(1, 6):
        # حساب عدد السجلات where choosenum = i
         count = Display_Data.objects.filter(url=url_to_check, choosenum=i).count()
         print(count)# إضافة عدد السجلات إلى القائمة
         countArray.append(count)
        return countArray  # الرابط موجود في قاعدة البيانات
    except Display.DoesNotExist:
        countArray= [0,0,0,0,0]
        return countArray
def display_video(request, url):
    # تشكيل الـ URL الكامل لإطار الفيديو على YouTube
    embed_url = f"https://www.youtube.com/embed/{url}"
    full_url = f"https://www.youtube.com/watch?v={url}"
    soup = BeautifulSoup(requests.get(full_url).content, "html.parser")
    title = soup.title.text
    # استخدم نموذج "display_data"
    countArry=check_url_exists(url)
# استخدم "Count" لحساب عدد السجلات
        

# طباعة النتيجة

       
                 

        # مرر الـ embed_url وعنوان الفيديو إلى القالب
    return render(request, 'display/videoA.html', {'embed_url': embed_url , 'title': title,'carry':countArry})  
and templet have include sentence 
    <div class="container mt-5">
    <div class="d-flex justify-content-start">>
        <!-- زر "نجحت" -->
        <button type="submit" name="CHOOSE"  value="1" class="btn btn-success mr-2">{{carray[0]}} نجحت</button>
        <!-- زر "فشلت" -->
        <button type="submit" name="CHOOSE" value="2" btn btn-danger mr-2">{{carray[1]}}فشلت</button>
        <!-- زر "تحتاج إلى مال" --> 
        <button type="submit" name="CHOOSE" value="3" class="btn btn-warning mr-2">تحتاج إلى مال{{carray[2]}}</button>
        <!-- زر "تحتاج إلى أدوات" -->
        <button type="submit" name="CHOOSE" value="4" btn btn-info mr-2">{{carray[3]}}تحتاج إلى أدوات</button>
        <!-- زر "مؤجل" -->
        <button type="submit" name="CHOOSE" value="5" class="btn btn-secondary">{{carray[4]}}مؤجل</button>
            <!-- زر "اخر نجاح" -->
            <button type="button" class="btn btn-success mr-2">اخر نجاح</button>
            <!-- زر "اخر فشل" -->
            <button type="button" class="btn btn-danger mr-2">اخر فشل</button>
    </div>
</div>
</form>

i have a django project i try to display vidio from youtube and user can evlaute it i saved the evlaution in data base i want to show data for every vidio that i show