Edit Javascript of a website before the page is loaded Chrome Extension

I am trying to make a chrome extension that can edit and remove parts of Javascript of a webpage preferably before the page is loaded.

For Example, the following script tag is within my test html website.

<script>
document.addEventListener("visibilitychange", onchange);
function onchange(){
    console.log('left');
}
</script>

This code tells the console when the user switches tabs. I would like to be able to edit this specific code only to prevent this from happening. Can I modify the text of JavaScript before runtime?

Clear canvas by JavaScript

I want to clear canvas for redrawing but after clear and when I click inside canvas for redrawing the old drawing that I cleared, it appears again

That is my canvas:

<canvas id="canvasFirst">
</canvas>

JavaScript code for clear:

    var canvas = document.getElementById('canvasFirst');
    let context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);

Can local .db files be opened with Expo-Sqlite?

I’m building a react native application on mobile (IOS and Android) with Expo and already have a .db file created from SQLite in which to make transactions with.

I’ve seen examples of projects which call a remote database from an API call as well as create a database if it does not exist already, but it’s not clear if this can open a local database file in my project. So far providing a filepath for the .db file is not able to be found.

import * as SQLite from 'expo-sqlite';

const path = './SQLite/TFData.db';

const db = SQLite.openDatabase(path);

If this is not an error on my part, I would like to know what can be done to read an existing database file that is already located in my project if expo-sqlite is not able to do this.

Get Total From a Chosen Array in ES6

I wanted to get the total productPrice from the chosenData array. I need to compare it from the mainData and only get its total value. My problem is that I’m getting undefined and how should I do it and is there a shorter way of doing it?

  const mainData = [
    {
        "id": "4324",
        "productName": "Apple",
        "productPrice": 250,
    },
    {
        "id": "656546b",
        "productName": "Banana",
        "productPrice": 500,
    },
    {
        "id": "5656",
        "productName": "Soup",
        "productPrice": 800,
    }
];

const chosenData = ['5656', '656546b']
  
  const newArray = chosenData.map((value, index) => ({
    productPrice: mainData.find((data) => data.id === value)
  }))


console.log(newArray.productPrice)

Why is this coming wrong?

    const n = Math.floor(Math.random());
    
    function checkIfEven(n) {
     if n % 2 == 0 {
        return 'It's an even number!';
    } else {
      return 'It's an odd number!';

}
}

    console.log(checkIfEven(n));

When I tried this the answer is coming that ‘n’ is unexpected identifier. Please explain how it came and how to correct it.

can you select a php imported html element with java script?

  1. i am currently trying to add a class to a html element that is imported by php.The php file contains a a tag element
<a class="felt" href="felt.php">Felt Products</a>

i can not see the class being added, why is this? can js not effect imported elements?

<?php include 'headtaglinks.html'; ?>  
<script>
 var element = document.getElementsByClassName("felt");
 element.classList.add("my-class");
</script>
  1. if i am being able to add a class to a php imported html element, will the added class stay when clicking on a href link? or will the class stay and be written unless i remove it?

I can’t consume data from API by fetch in JavaScript [duplicate]

I’m trying to get data via JavaScript from an API hosted on Heroku, but it’s not working. The following error appears in the browser: “failed to load response data no data found for resource with given identifier“.

The code I’m using is this one below:

fetch('https://litrometro-api.herokuapp.com/')
  .then(function(response){
    return response.json();
  })
  .then(function(data){
    console.log(data[0])
    console.log(data);   
  });

vee-validate v-text field in modal

context

I’m working with a field list where need through the edit button, go to a modal to edit or add a new field for this list.(I’m using vue and vuetify)

I’m having problems with the modal when I try to validate a name of these fields don’t pass if go blank (v-text-field).

My form (image1), When I press add field, the response in console is undefined independing if the field is blank or not.
enter image description here

Here part of my code

I did the global import

import Vue from "vue";
import { ValidationObserver, ValidationProvider, extend } from 'vee-validate'
import { required } from 'vee-validate/dist/rules'

extend('required', required)
Vue.component('ValidationProvider', ValidationProvider);
Vue.component('ValidationObserver', ValidationObserver)

Here is my component code
https://codepen.io/fmoraless/pen/NWXvKLQ
The main section is where is validation tags of vee-validate in template.

template section

<validation-observer ref="v-card">
      ...
      ...
          <v-col cols="12" :md="6">

              <validation-provider
                  v-slot="{ errors, validate }"
                  vid="label"
                  :rules="{ required: true }"
              >
                <v-text-field
                  v-model="field.label"
                  :label="$t('Label')"
                  :placeholder="$t('Please enter a label')"
                  hide-details="auto"
                  filled
                  dense
              >
                </v-text-field>
              </validation-provider>

          </v-col>
         ...
       ....
    </validation-observer>

script section

    <script>
import {field_types, payment_methods} from "../../helpers/options";
import {widthExtraSmallDialog as width} from '../../helpers/responsive';
import { bus } from "../../app";
import { Field, validate } from 'vee-validate';

export default {
  name: "MilestoneFieldsEdit",
  data () {
    return {
      visible: false,
      index: null,
      field: {
        mobile_activity_id: 1,
        label: "",
        is_required: true,
        dynamic_cols: [],
        sort: 1,
        _destroy: false
      },
       ....
    }
  },
  created() {
    ....
  },
  computed: {
    ...
  },
  watch: {
   .....,
  },
  methods: {
    ...
    async handleAdd() {
      try {
        await this.$refs.form.validate()
        $this.$emit("add", {
          ...this.field,
          sort: this.index + 1,
        });
        this.$emit("close");
        this.handleReset();

      } catch ({response}) {
        console.log('response', {response})
        if ({response} == undefined) {
          this.$refs.form.setErrors(response.data.errors)
        }
      }
    }

expected results

See a validation message after press add new field.

code

Here mi code pen with extended components

If you can give tips or hint to resolve, I really appreciate it

Sequentialization of Object keys in javascript

I am having an array

{
    A1:{KEY:VALUE},
    A2:{KEY:VALUE},
    A14:{KEY:VALUE},
    A15:{KEY:VALUE},
    B1:{KEY:VALUE},
    B3:{KEY:VALUE},
    B12:{KEY:VALUE},
    B14:{KEY:VALUE},
    B15:{KEY:VALUE},
}

I want to have key names in order as below:

{
    A1:{KEY:VALUE},
    A2:{KEY:VALUE},
    A3:{KEY:VALUE},
    A4:{KEY:VALUE},
    B1:{KEY:VALUE},
    B2:{KEY:VALUE},
    B3:{KEY:VALUE},
    B4:{KEY:VALUE},
    B5:{KEY:VALUE}
}

What I did is created an array with 2 elements as below:

var loopIterationArray = [A,B] // Depending on Object elements value of this array can be [A,M]

Now I was trying to iterate between all alphabets between these two elements of array and try to change key in sequential order.

Is there any way to do it efficiently? Please do let me know if I was not clear on any part

Unexpected token “:” error after fetching json file [duplicate]

I am trying to use fetch to import a local json file in JavaScript but I keep getting the error for the 2nd line of the json file:

Uncaught SyntaxError: Unexpected token “:”

Here is my json file:

{
    "items": [
        {
            "key 1": "abc",
            "key 2": {
                "xyz": [
                    {
                        "name": "abc",
                        "version": "1.0.0",
                    },
                    ...                
                ]
            },
            "key 3": {
                "...": [
                    {
                        ...
                    },
                    ...                
                ]
            },
        },
        ...
    ]
}

I’ve used an online json validator, and confirmed that my json.

Here is my JavaScript code:

<script src="file.json">
    fetch("./file.json")
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err))
</script>

how can i connect all 3 data tables in just one statement?

Hi I’m just a newbie in coding and i encounter this problem, where in i have 3 tables and i want them to be connected to each other how can i connect them?

The code I’m using is this one.

<?php $conn = mysqli_connect('localhost','root','','elearningsystem_db');?>

query(“SELECT * FROM users WHERE username = ‘$username’ and password = ‘$password’ $type”);
if($qry->num_rows > 0){
foreach($qry->fetch_array() as $k => $val){
if($k != ‘password’)
$_SESSION[‘login_’.$k] = $val;
}
echo 1;
}else{
echo 2;
}
?>

how can I insert the table named facultyData and studentData.

any help will be appreciated!

How to add a Countdown Timer with a value returned from Database using Ajax and displayed within a

Really stuck on this one. I have created an admin panel which retrieves data from MySQL database and displays the results within HTML using a Data table using Ajax/Json. This all works fine. One of the fields that is retrieved is a time which is given by the user in hours and minutes displayed as – 00:00. I need to take this time and make it countdown to zero within the tag.
One other thing I should add is the page refreshes every minute as it needs to collect data often.

Can anyone help with this?

Here is the code so far HTML –

    <html> 
    <div class="table-responsive">
    <table class="display datatables" id="tableBody"></table>
    </div>                        
    </html>

And here is my Javascript –

    `$( document ).ready(function() {
$.ajax({
    url: 'php/fetch.php',
    mothod: 'post',
    dataType: 'json',
    success:function(data){
        let string = '';
                                        
        $.each(data, function(key, value){
            string += `<tr>
            <td>${value['timesubmit']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['operatorname']}</td>
            </tr>`;
            string += `<tr>                
            <td># ${value['trucknumber']}</td>
            </tr>`;
            string += `<tr>                
            <td>${value['truckleaving']}</td>
            </tr>`;
            string += `<tr>
            <td>: ${value['jobstatus']}</td>
            </tr>`;
            string += `<tr>
            <td>${value['work']}</td>
             </tr>`;
            string += `<tr>
            <td>Time Left: ${value['typea9']}</td>  
             </tr>`;
        });
        

        $('#tableBody').append(string);
        $("#tableBody td:contains(Work: Yes New Job)").attr("style","background- 
        color:#44fa04");
        $("#tableBody td:contains(Work: No New Job)").attr("style","background- 
        color:#f80a26");
        $("#tableBody td:contains(Truck Leaving: Clean)").attr("style","background- 
        color:#288e04");
        $("#tableBody td:contains(Truck Leaving: Dirty)").attr("style","background- 
        color:#a07604");
        $("#tableBody td:contains(Truck Leaving: Unused)").attr("style","background- 
        color:#a5a39e");
    },
    error:{

    }
       });`

The ${value[‘typea9’]} is the value with the time in it which needs turning into a countdown.

Any help would be much appreciated with this.

Block disappears if there is no image in it

All health and happiness! A written script that should iterate through all the pictures, if the pictures did not load, then the script should hide the parent block under the .Parent_block class, that is, I have 3 blocks, there is a picture in the central block, but not in the other two, which means they should have property display:none

But I did something wrong. Where did I make a mistake?

let parent_block = document.querySelectorAll('.Parent_block');
let image_b = document.querySelectorAll('.Child_Img');

image_b.forEach(function(){

if(image_b.onerror){

for(let parent_block of hide){
hide.style.display = 'none';    
}

}

})
.Parent_block{
width:30%;
margin:0;
padding:0;
margin-left:10px;
margin-top:10px;
border:1px solid black;
display:inline-block;
height:250px;
}

img{
height:inherit;
width:100%;
<figure class="Parent_block"> <!-- ***** this block should disappear *****  =( -->
 
<img class="Child_Img" src="">

<figcaption class ="Img_text">1</figcaption> 

</figure>


<figure class="Parent_block"> 
 
<img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg">

<figcaption class ="Img_text">2</figcaption> 

</figure>


<figure class="Parent_block"> <!-- ***** and this one too *****  =( -->
 
<img class="Child_Img" src="">

<figcaption class ="Img_text">3</figcaption> 

</figure>

Web Speech API reads in wrong language at first and then the right language

i have tried to make a text to speech on my web page with the Web Speech API. Found a code to help me accomplish but the main problem is when i press the button first it reads in german and then when i press again, it reads in Turkish (which i actually want). 2nd problem is in safari the voice list changes but i want only a voice that is in Turkish. And lastly, cancel button won’t stop.
(the “console.log(voices[3])” gives out “undefined” at first and then when i press 2nd time, it gives out the info for Turkish voice). I can comment if anything else is needed, pardon my poor grammar if i could not explain properly, Thank you.

 <input type="button" id="cancelBtn" value="Cancel">
                    <button id="speakBtn" type="button" class="btn btn-outline-primary btn-xs rounded pull-right" style="padding: 4px 7px; margin-top: 15px;">Haberi Oku <i class="fa fa-bullhorn"></i></button>

                    <?php
$pt=$row['postdetails'];
              echo  (substr($pt,0));?>

                    <script>
                        function textToSpeech() {
                            //alert("Test"); //for test only.
                            const speech = new SpeechSynthesisUtterance();
                            let voices = speechSynthesis.getVoices();
                            let convert = document.getElementById("textID").innerHTML;

                            speech.text = convert;

                            speech.volume = 1;
                            speech.rate = 1;
                            speech.pitch = 1;

                            speech.voice = voices[3];
                            console.log(voices[3]);
                            speechSynthesis.speak(speech);
                        }


                        function pause() {
                            window.speechSynthesis.pause();
                        }


                        function stop() {
                            window.speechSynthesis.cancel();
                        }

                        speakBtn.addEventListener('click', textToSpeech);
                        pauseBtn.addEventListener('click', pause);
                        cancelBtn.addEventListener('click', stop);
                    </script>