How to download text or byte array in the background avoiding CORS?

I’m experimenting with some type of online run-time-packages (private projects). Which works very well with images and audio. Now I’m trying to figure out if there is ANY way to get text or binary data from a “cloud” into the browser executing my js code. I’m running an html file like “file:///C:/blahblah/index.html”. I know CORS and stuff is build in for security reasons. But since I can use images and audio with no problem, why not simple text?

The question is: How do I get text from an online resource, avoiding CORS and without bothering the user to download it?

// working example
function onResourceLoaded(e)
{
    console.log(e);
}
var img = new Image();
img.onload = onResourceLoaded;
img.src = "http://www.clker.com/cliparts/3/4/3/1/1238701861238753675qubodup_Public_Domain_Audio_Symbol.svg.thumb.png";

// not working, CORS error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.dwsamplefiles.com/?dl_id=176");
//xhr.responseType = "text/plain";
xhr.onload = onResourceLoaded;
xhr.send();

metodo http DELETE y PUT me devuelve net::ERR_EMPTY_RESPONSE

Hola estoy desarrollando mi primera api rest con php y js. Estoy haciendo un editor de archivos .txt utilizando los metodos http de POST, GET, PUT y DELETE. Todo bien el crear y regresar datos por POST y GET, pero con PUT y DELETE me delvuelve en consola lo siguiente:

net::ERR_EMPTY_RESPONSE

aqui mis metodos de PUT y DELETE en js:

// METODO DELETE
function httpDelete(url) {
    var http = new XMLHttpRequest();

    http.open("DELETE", url, true);
    http.send();

    http.onreadystatechange = function() {
        if(this.status == 200 && this.readyState == 4) {
            var respuesta = JSON.parse(this.responseText);

            if(respuesta.estado == 'eliminarArch') {
                mostrarArchActualizados(entrada = "mostrar");
                limpiar();
            }
        }
    }
}

// METODO PUT
function httpPut(url) {
    var http = new XMLHttpRequest();

    http.open("PUT", url, true);
    http.send();

    http.onreadystatechange = function() {
        if(this.status == 200 && this.readyState == 4) {
            var respuesta = JSON.parse(this.responseText);

            if(respuesta.estado == 'actualizado') {
                mostrarArchActualizados(entrada = "mostrar");
                limpiar();
            }
        }
    }
}

aqui mi php donde recivo todas las solicitudes:

switch($_SERVER['REQUEST_METHOD']) {
        case 'GET':
            break;
        case 'POST':
            break;
        case 'DELETE':
            if(isset($_GET['eliminar'])) {                
                if(eliminarArchivo($_GET['eliminar'])) {
                    $respuesta['estado'] = 'eliminarArch';
                    http_response_code(200);
                } else {
                    http_response_code(500);
                }

            } else {
                http_response_code(404);
            }

            break;

        case 'PUT':
            if(isset($_GET['archivo']) && isset($_GET['actualizar'])) {       

                if(actualizarArchivo($_GET['archivo'], $_GET['actualizar'])) {
                    $respuesta['estado'] = 'actualizado';
                    http_response_code(200);

                } else {
                    http_response_code(500);
                }

            } else {
                http_response_code(404);
            }

            break;

        default:

            break;
    }

    header("Content-type: application/json");
    echo json_encode($respuesta);

How to get an input list data-value content, after selection ended, using pure javascript?

I have defined a searchable select list, as defined below. What I would like is to get the data-value field once a selection is made, while the user will still see the option value string. This field will contain the internal id of the entry.

If I define this id, as a value attribute, the dropdown list will show both the id and the string , and after selection only the id will be visible in the input field.

I’ve found some posts taking about using data-* attributes to work around this problem, but for some reasons, I’m not able to get this value from the input field, after the selection was completed.

Any idea how I can achieve this?

Thanks

PS: I’m only interested in pure JavaScript solutions.

<html>
<head>
<script>
function onchangeTest(){
alert(document.getElementById("input").value);
}
</script>
</head>
<body>
    <div id="share">
        <input type="text" id="input" list="datalist" onchange="onchangeTest()">

        <datalist id="datalist">
           <option data-id="1">Foo</option>
           <option data-id="2">Bar</option>
           <option data-id="3">Baz</option>
           <option data-id="4">Foo Bar</option>
           <option data-id="5">Bar Baz</option>
        </datalist>
    </div>

</body>
</html>

Running more than one function in Node.js

I am having trouble understanding why my application will terminate after running only one function. I have coded the application as follows…

const readline = require('readline');

const io = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log(
  'Welcome. This application will check if a given year is a leap year.'
);

checkYear();

function checkYear() {
   io.question('Check which year? ', function (year) {
      year % 100 === 0 && year % 400 !== 0
         ? false
         : year % 4 === 0
         ? console.log(year + ' is a leap year.')
         : console.log(year + ' is not a leap year.');
      });

   io.question('Check another year? y/n'), function(response) {
      if (response.toLowerCase === 'y') {
         checkYear();
      } else {
         io.close();
      }
   }
};

I have also tried breaking the second prompt into its own function and calling both checkYear and checkAgain back-to-back, but I get the same result. What do I need to do to make the io.question(‘Check another year’) prompt run after the application responds to the first input?

“Why isn’t my Discord bot sending messages to new members when they join the server?”

The bot should bring the newcomer into the ‘verificaton’ channel and ask them questions to verify the user but when they join they see Rules Screening page and have to agree to rules to proceed. And that’s i think might be the issue because the bot tries the access the user to bring them into the ‘vefification’ channel. How can I solve that issue so the bot would wait until the user agrees to all rules and does all the ‘Welcome Page’ stuff to finally bring them into the necessary channel and ask them necessary questions?

My bot’s code:

const fs = require('fs');
const { Client, GatewayIntentBits } = require('discord.js');
const config = require('./config.json');

const client = new Client({ 
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers, GatewayIntentBits.MessageContent] 
});

// Replace this with your questions and answers
const questions = [
    { question: 'What is the capital of France?', answers: ['Paris', 'London', 'Berlin'] },
    { question: 'What is the largest mammal?', answers: ['Blue Whale', 'Elephant', 'Giraffe'] },
    { question: 'What is the smallest planet in our solar system?', answers: ['Mercury', 'Mars', 'Pluto'] },
];

function randomizeQuestions() {
    const randomizedQuestions = [];

    // Fisher-Yates shuffle algorithm
    for (let i = questions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [questions[i], questions[j]] = [questions[j], questions[i]];
    }

    for (const question of questions) {
        randomizedQuestions.push({ ...question });
    }

    return randomizedQuestions;
}

client.once('ready', () => {
    console.log('Bot is ON!');
});

client.on('guildMemberAdd', async member => {
    const unverifiedRole = member.guild.roles.cache.get('************');
    member.roles.add(unverifiedRole);

    const verificationChannel = member.guild.channels.cache.find(channel => channel.name === 'verification');

    if (!verificationChannel) {
        console.error('Verification channel not found');
        return;
    }

    try {
        await verificationChannel.send(`${member.user.username}, welcome to the server! Please answer the following questions in this channel to verify yourself:`);

        const randomizedQuestions = randomizeQuestions();

        for (let questionObj of randomizedQuestions) {
            const question = questionObj.question;
            const answers = questionObj.answers;
            const correctAnswer = answers[0];

            const answerList = answers.map((answer, index) => `${index + 1}. ${answer}`).join('n');
            
            await verificationChannel.send(`**${question}**nn${answerList}`);
            const filter = m => m.author.id === member.user.id && !isNaN(m.content) && m.content >= 1 && m.content <= answers.length;
            const collected = await verificationChannel.awaitMessages({ filter, max: 1, time: 30000, errors: ['time'] });

            if (collected.first().content !== '1') {
                await verificationChannel.send(`${member.user.username}, sorry, your answer is incorrect. You have been removed from the server.`);
                return member.kick('Failed verification');
            }
        }
        await member.roles.add('***********');
        await verificationChannel.send(`${member.user.username}, congratulations, you have successfully verified your account! Welcome to the server.`);
    } catch (error) {
        console.error(error);
    }
});

client.login(***********);

How to create a non-incognito window from an incognito window

I have a Chrome extension that the user can enable for incognito, which works as intended. Upon button press, I’m trying to force a specific url to NOT open incognito, even when initiated from within an incognito window.

chrome.windows.create({ 'url': 'https://www.google.com', 'incognito': false });

But it only creates another incognito window.

Is it possible to create a non-incognito window and/or tab from within an incognito window?

accessing variable outside onload function [duplicate]

function addTodo() {

const file = document.getElementById('imageInput').files[0];
const reader = new FileReader();
reader.readAsDataURL(file);

reader.onload = function(e) {
    const dataURL = reader.result;
   
    let imageRow = `
      <img src="${dataURL}" alt="img"/>
    `;
};

const id = '' + new Date().getTime()

}

How can i use imageRow after the reader.onload function ends? I want to use it after the random id is generated at the end. Can someone guide please

Why does it not set the SameSite cookie attribute?

I am accessing youtube videos on my website and getting an error, that I should specify my SameSite cookies manually but when I do so, it just doesn’t work and gives me the same error.

The error message:
Indicate whether a cookie is intended to be set in a cross-site context by specifying its SameSite attribute.

My try plain with Javascript:

<script>
    document.cookie = "AC-C=ac-c;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax";
</script>

My try with js-cookie:

<script type="module" src="/js-cookie/js.cookie.mjs"></script>
<script type="module">
    import Cookies from '/js-cookie/js.cookie.mjs'

    Cookies.set('name', 'value', {
        sameSite: 'none',
        secure: true
    });
</script>

e.preventDefault is not a function (React)

I am using React to make a form that will make a POST to MongoDB, what happens is that when I start trying to fill the form I get the following error:

e.preventDefault is not a function
TypeError: e.preventDefault is not a function
    at handleChange (http://localhost:3000/main.451f9e824d0c94815e46.hot-update.js:96:7)
    at http://localhost:3000/static/js/bundle.js:75093:9
    at http://localhost:3000/static/js/bundle.js:65561:23
    at http://localhost:3000/static/js/bundle.js:75185:20
    at http://localhost:3000/static/js/bundle.js:65561:23
    at http://localhost:3000/static/js/bundle.js:75552:5
    at http://localhost:3000/static/js/bundle.js:65561:23
    at http://localhost:3000/static/js/bundle.js:66024:33
    at http://localhost:3000/static/js/bundle.js:64750:23
    at http://localhost:3000/static/js/bundle.js:75552:5

this is the code where the preventDefault is located:

const handleSubmit = async (e) => {
    e.preventDefault();

    const res = await fetch("http://localhost:5001/client/projects", {
      method: "POST",
      body: JSON.stringify(project),
      headers: { "Content-Type": "application/json" },
    });

    const data = await res.json(project);
    console.log(data);
    console.log(project);
  };

const handleChange = (e) => {
    e.preventDefault();
    setProject({ ...project, [e.target.name]: e.target.value });
  };

I am very grateful to everyone who can help me 🙂

3D object Rotation with Javascript

i can rotate a 3d object with swiping one finger

var curPos = undefined;

var transform = script.getSceneObject().getTransform();

var speed = 10.0;

script.createEvent("TouchStartEvent").bind(function (eventData) {

    curPos = eventData.getTouchPosition();

});

script.createEvent("TouchMoveEvent").bind(function (eventData) {
    

    if(!curPos)
    
        return;

    var nextPos = eventData.getTouchPosition();

    var deltaX = nextPos.x - curPos.x;

    var deltaY = nextPos.y - curPos.y;


    var mat = transform.getInvertedWorldTransform();

    var axisX = mat.multiplyDirection(vec3.up());

    var deltaRotX = quat.angleAxis(deltaX * speed, axisX);

    var axisY = mat.multiplyDirection(vec3.right());

    var deltaRotY = quat.angleAxis(deltaY * speed, axisY);

    var rot = transform.getLocalRotation().multiply(deltaRotX).multiply(deltaRotY);

    transform.setLocalRotation(rot);

    curPos = nextPos;
             
});

enter image description here

but when i try to scale it with two fingers, it keeps rotating

any suggestions please, i use a simple script for the rotation

THANKSenter image description here

I need to block two fingers or more when touching the screen

How to fetch the id of an item in Django when using JSON to fetch from the database

I have a Django template whereby I am looping through several items in the homepage. When an item is clicked, a modal which I have included by importing it should be shown and data related to the clicked item displayed. I am using JSONResponse to prepopulate the modal. Once the modal is shown, I want to create a checkout session which will require the id of the item being referred to in the modal. I am stuck at how to get the id.
Here is the script for showing the modal and prepopulating it:

let modal = document.getElementById("modal");
modal.style.display = "none";

function modalHandler(val, content_id) {
  if (val) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        let data = JSON.parse(this.responseText);
        document.getElementById("subtotal").innerHTML = data.subtotal;
        document.getElementById("taxes").innerHTML = data.taxes;
        document.getElementById("website_fee").innerHTML = data.website_fee;
        document.getElementById("total").innerHTML = data.total;

        fadeIn(modal);
      }
    };
    xhr.open("GET", "/modal-content/" + content_id + "/", true);
    xhr.send();
  } else {
    fadeOut(modal);
  }
}

Here is the views.py which returns the JSON data:

def modal_content_view(request, content_id):
    my_model = get_object_or_404(MyModels, content_id=content_id)
    print(f"the model is {my_model.username}")
    data = {
        'subtotal': my_model.username,
        'taxes': '2.60',
        'website_fee': '0.87',
        'total': '23.47',
        'content_id':my_model.content_id
    }
    return JsonResponse(data)

Here is the script that is supposed to fetch the data when the checkout button is clicked:

<script type="text/javascript">
        var checkoutButton = document.getElementById('checkout-button');
       
        checkoutButton.addEventListener('click', function() {
        fetch("{% url 'checkout' content_id %}", {
        method: 'POST',
        data: JSON.stringify({
              amount: "{{ cost }}" * 100,
              description: "{{ title }}",
              gig_id: "{{ gig_id }}",
            }),
        })
        .then(function(response) {
        return response.json();
        })
        .then(function(session) {
        return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function(result) {
        if (result.error) {
        alert(result.error.message);
        }
        })
        .catch(function(error) {
        console.error('Error:', error);
        });
        });
        </script>

Here is the view that handles the content_id passed from the script above:

@csrf_exempt
def create_checkout_session(request, content_id):
    model = MyModels.objects.get(content_id=content_id)
    subscription = Subscription(model=model, is_subscribed=False, user=request.user)

And here is the onclick function that triggers the modal to show:

onclick="modalHandler(true, '{{content.model.content_id}}')"

My question is how do I pass the ‘content_id’ from the modal to the script that handles checkout

Only change single elements style from many similar class selector

I found this following code which changes style of elements through clicking each of it.
from border:1px solid #dedede to 2px solid #f60000.

<script>
var ckStyle = document.getElementsByClassName("cls");
for (var i = 0; i < ckStyle.length; i++) {
    ckStyle[i].addEventListener('click', function() {
        this.style.border = "2px solid #f60000"; 
        }, false);
    }  
</script> 

I try like this below, but not working:

<script>
var ckStyle = document.getElementsByClassName("cls");
for (var i = 0; i < ckStyle.length; i++) {
    ckStyle[i].addEventListener('click', function() {
        this.style.border = "2px solid #f60000"; 
        }, false);
    return(
        this.style.border = "1px solid #dedede"; 
      );
    }  
</script> 

Default style in CSS:

<style>
.cls{border:1px solid #dedede;}
</style>

Here’s The HTML:

                <div class="cCont1">
                    <ul class='wr'>
                        <li class='cls color1'>Kuning</li>
                        <li class='cls color2'>Putih</li>
                        <li class='cls color3'>Hijau</li>
                        <li class='cls color4'>Biru</li>    
                        <li class='cls color5'>-</li>         
                        <li class='cls color6'>-</li>  
                        <li class='cls color7'>-</li>  
                        <li class='cls color8'>-</li>  
                        <li class='cls color9'>-</li>  
                        <li class='cls color10'>-</li>                        
                    </ul>
                </div>
                <div class="cCont2">
                    <ul class='wr'>
                        <li class='cls color1'>Biru</li>
                        <li class='cls color2'>Hitam</li>
                        <li class='cls color3'>Putih</li>
                        <li class='cls color4'>Merah</li>
                        <li class='cls color5'>Coklat</li>
                        <li class='cls color6'>Abu-abu</li>   
                        <li class='cls color7'>-</li>  
                        <li class='cls color8'>-</li>  
                        <li class='cls color9'>-</li>  
                        <li class='cls color10'>-</li>                        
                    </ul>
                </div>

When I click color1 in, say, cCont2 the style of the cls element will be like 2px solid #f60000. Then I click other element (e.g. color2) and again the style change as in color1.

What I want is: when I click color1 and color2, only one element will be styled.
On the other hand, when I click color1 and soon after that I click color2 the style will change in color2 and color1 turn into the default as in CSS above.

Style only works on one element. And, previous element turns into the default.