On safari browser, paste content programmably will show system paste menu sometimes

When you want paste something in a contenteditable element by using javascript, there are two ways.

  • Using the deprecated method document.execCommand('paste')
  • Or using the new Clipboard API navigator.clipboard.read()

On safari browser, paste content programmably will show system paste menu sometimes, not always. The above two methods’s behavior are same.

Is there anyway to disable this?

My safari browser: v15.0.

Test page ==> https://codepen.io/netsi1964/pen/QbLLGW?editors=0010

enter image description here

ES6 Solution for OG:image tag on amazon urls

trying to display OG:image data from Amazon product urls
e.g – https://www.amazon.com/-/es/Lenovo-Chromebook-Flex-procesador-82HG0006US/dp/B08T6N424Z/

Unfortunately Amazon doesn’t have an meta tags in their head but you get a nice preview whenever you send a URL in iMessages or post in Facebook.

Was wondering if anyone had insight in retrieving open graph image data for amazon product urls

Thanks!!

Workaround for IoT device without CORS headers

I have an IoT device with an HTTP API – I am building a very simple HTML + JS interface with no server component.

Using a simple XMLHttpRequest I am able to make calls to the API however I am hitting an issue with CORS; all calls to the API respond with a 200, and take the proper action on the IoT device; the calls return the proper values according to the network inspection tab however no data is returned to the callback.

Given two functions:

// Helper API Request Method
function call(host, cmd, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function(data) { console.log(data); };
        xhr.open("GET", "http://" + host + "/httpapi.asp?command=" + cmd);
        xhr.send();
}

// Set output volume level (0->100)
function a_vol(master, vol) {
        call(master, "setPlayerCmd:vol:" + vol);
}

When I call the function in the JS console, I don’t have access to the returned object:

a_vol("10.3.106.120", 80);
undefined
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.3.106.120/httpapi.asp?command=setPlayerCmd:mute:0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Given that I can not edit the firmware of the device to include the CORS headers, and that the device still responds as expected to the API commands, what can I do to avoid this error message and access the returned object?

Google Apps Script – script runs twice?

I’m fairly new to Google Apps Script and I may be missing something, but I’m trying to make a very basic script for testing purposes and literally everything I write runs twice. Absolutely no idea why. Can someone point me in the right direction for some reading I can do on this?

Right now, I’m just working with the Calendar API and getting the names of my calendars, but they always print twice. Here is the code:

function myFunction() {
  let calendars = CalendarApp.getAllCalendars();
  let haveCalendar = false;
  for(i=0;i<calendars.length;i++){
    if (calendars[i].getTitle() == "Holidays"){
      Logger.log(calendars[i].getTitle());
      haveCalendar = true;
    } else if (haveCalendar == true || calendars[i].getTitle() != "Holidays"){
      Logger.log("already have calendar");
    }
  }
}

myFunction();

The current output for this is:

already have calendar
already have calendar
Holidays
already have calendar

already have calendar
already have calendar
Holidays
already have calendar

I’m completely baffled. Any help would be greatly appreciated.
Thanks in advance!

firebase initializeApp/getMessaging (undefined)

I am trying to implement firebase on my server and I am coming with a lot of errors. I have been trying for a few hours now with a bunch of tweaks and different ways to try and get this working, but no such luck. This is where my code sits now:

  <script type="module">
    import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-app.js'
    import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-analytics.js'
    import { getMessaging } from 'https://www.gstatic.com/firebasejs/9.6.3/firebase-messaging.js'
  </script>

  <script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script>

  <script>
  const app = firebase.initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
  });
  console.log(app);
  const messaging = getMessaging();
  getToken(messaging, { vapidKey: '' }).then((currentToken) => {
  if (currentToken) {
  console.log('got token');
  } else {
      // Show permission request UI
      console.log('No registration token available. Request permission to generate one.');
      // ...
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    // ...
  });
  </script>

and the error i am getting is

Uncaught ReferenceError: getMessaging is not defined
    at index.html:20:21

I have tried different variations like

const messaging = firebase.getMessaging();

and

const messaging = app.getMessaging();

but it always come back undefined. Shouldn’t it be pulling from the import library?
Also, I know the documents say all you need is const app = initializeApp({}) but that was also returning undefined until I imported this script <script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script> and called to it using firebase.initializeApp() .. I don’t even know if that is the most up-to-date resource. I have installed all of the node_modules with NPM but I don’t really know how node works and the "firebase/app" paths weren’t working for me. Any help or guidance would be greatly appreciated, thank you!

How to display the username in the admin section, based on the login user who enters the system (ReactJS)

I have a login form that contains email and password, how do I get the username from the login used and displayed in the “Admin” sidebar and will be the name of the logged in user

here’s the image : (https://i.stack.imgur.com/zE7t3.png)

btw, I cant post the image, because it says “You need at least 10 reputation to post images.”

Rounding off to 2 decimal places (Adobe Acrobat)

How do I specify a number format with 2 decimal places for a field that already is using a custom format script?

I have a form that has many sub-total and total fields. I want those fields to:
(1) have PHP unit
(2) have comma separator
(3) display as empty if the value is zero

So I have entered the following custom format script for the field:

var x = event.value;
var n = x.toString().split(".");
n[0] = n[0].replace(/B(?=(d{3})+(?!d))/g, ",");
if(event.value == 0) event.value = "";
else event.value = "Php "+ n.join(".");

All conditions are met but I want the result to be in 2 decimal places only, there are times that 2 decimal places is the result but most of the time it shows 3 or more decimal places.

(Windows 10) Changing multiple folder’s icon (customized icon) at once [closed]

I have about 30 folders, each has a movie inside, and due to my ocd I really wanted each folder’s icon to be the cover of that movie. So I converted the posters from .jpg to .ico online, renamed them to “icon”, and put them inside the folder. Now I have 30 folders with 2 files inside: the movie, and the icon.ico file. I tried looking for a solution online but can’t find any 🙁

regex replace for multiple string array javascript

I have a array of string and the patterns like #number-number

If the # and single digit number before by hyphen then replace # and add 0

If the # and two or more digit number before by hyphen then replace remove #

I got stuck and how to do in javascript

In #number,

if # and number is two or more digits before hyphen(-) remove # only 
eg
#162-7878 should be 162-7878, #12-4598866 should be 12-4598866)


if # and number is single digit before hyphen(-) remove # and add 0 
eg
#1-7878 should be 01-7878

let arrstr=["#12-1676","#02-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988"]

for(let st of arrstr)
 console.log(st.replace(/#?(d)?(d-)/g ,replacer))
 
 function replacer(match, p1, p2, offset, string){
  let replaceSubString = p1 || "0";
  replaceSubString += p2;
  return replaceSubString;
 }

Make HTTP request from chrome:// URL in JavaScript

I am trying to process a bunch of data on a URL prefixed with chrome://, it being chrome://webrtc-internals/. To do this, I am sending it to a server via AJAX request from code I ran manually in the inspect tool.

But I assume for security purposes, any requests to outside URLs (ones that don’t start with chrome://) fail, and I don’t even see them in Wireshark.

const req = new XMLHttpRequest();
req.open("POST", "https://example.com", true);
req.send();

enter image description here

Is there any way I can disable this so I can make requests to other URLs?

Is it a good idea to create a programming language in Perl [closed]

I’ve been creating my own programming language for fun, and I’m using JavaScript (NodeJS).
However, as my code gets complicated, my language gets slower. So, I’m considering to convert what I have written in JavaScript to Perl (I’m not very good at C++, C, and other lower-level languages). And I have read that Perl is good at parsing and quite fast.

My question is that if it’s a good idea to write a programming language in Perl.

Why is AWSAppSyncClient IAM throwing IncompleteSignatureException error

i’m trying to implement an unauthenticated graphql request using IAM
i’m using AWSAppSyncClient from https://www.npmjs.com/package/aws-appsync

import Auth from '@aws-amplify/auth'
import AWSAppSyncClient from 'aws-appsync'
new AWSAppSyncClient({
  // @ts-ignore
  url: API_URL,
  // @ts-ignore
  region: process.env.aws_s3_region,
  // @ts-ignore
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: () => Auth.currentCredentials(),
  },
  // Uses Amazon IAM credentials to authorize requests to S3.
  complexObjectsCredentials: () => Auth.currentCredentials(),
  disableOffline: true,
})

i’ve already setup unauthenticated access to AWS AppSync and configured the unauthenticated role being used.

when i tried to do a request the response was 403

{
  "errors" : [ {
    "errorType" : "IncompleteSignatureException",
    "message" : "'accept' is named as a SignedHeader, but it does not exist in the HTTP request."
  } ]
}

Request Headers:

:authority: <URL>
:method: POST
:path: /graphql
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: AWS4-HMAC-SHA256 Credential=<KEY>/20220114/eu-central-1/appsync/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date;x-amz-security-token, Signature=87b4a4bf3db5d7a0084491f3947bc4414890887f5cd600b2bc14612e608db5d4
cache-control: no-cache
content-length: 374
content-type: application/json; charset=UTF-8
origin: http://localhost:3001
pragma: no-cache
referer: http://localhost:3001/
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
x-amz-date: 20220114T013513Z
x-amz-security-token: <TOKEN>
x-amz-user-agent: aws-amplify/1.8.1

Based on the error response it says that i’m not sending accept as a header but based on the headers accept is sent in the headers

How do I end the inner part of this nested loop but have the larger overall nested loop continue?

I’m working on a part of a minimax AI for a Connect Four board.

I have a parallel gameboard to test that looks like this:

let parallelBoard = [
[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14],
[15,16,17,18,19,20,21],
[22,23,24,25,26,27,28],
[29,30,31,32,33,34,35],
[36,37,38,39,40,41,42]
];

The findAvailableSpots(board) function gives me an array consisting of the numbers in the first row that are still available for play. I use the first row to determine this because I splice “Red” or “Yellow” into the array whenever a spot is taken, and if the first row for that column is occupied, it cannot be selected anymore.

Then I loop through the length of available spots, and take each one as the index of the column I want to put a marker into and test.

Next, for each one of these available spots, I loop upwards from the bottom or sixth row to place the token where there is no “red” or “yellow” string in that spot.

I would like it to stop once it finds a spot and move on to the next number in the parallelAvailable array.

But if I don’t put in a return, it puts a token in every row of that column.

If I do put in a return, it breaks after splicing [parallelAvailable][0].

I would like it to run the i loop to see which row it can put a token into, and then move on to the next in [parallelAvailable][s].

What should I do? Am I placing the return in the wrong place, or is there a better way to do this altogether, maybe with another if condition?

function pickBestMove() {
//     let bestScore
//     let bestColumn

 let parallelAvailable = findAvailableSpots(parallelBoard)
 console.log(parallelAvailable)

 for (s=0; s<parallelAvailable.length; s++) {
    let i;
    let j = parseInt(parallelAvailable[s] - 1)
    console.log(j)
    for (i = 5; i > -1; i--) 
        {if (Number.isInteger(parallelBoard[i][j])) {
            parallelBoard[i].splice((j), 1, currentPlayer)
            }

    //         let positionScore = scorePosition (parallelBoard, currentPlayer)
    //         console.log(gameboard[i][j] + " gets " + positionScore)
    //         parallelBoard[i].splice((indexPick), 1, gameboard[i][j])
            
    //             if (positionScore > bestScore) {
    //                 bestScore = score
    //                 console.log(bestScore)
    //                 bestColumn = s
    //                 console.log(bestColumn)
    //             }
    //         // return
    //        }
    //     }
    }
    // return bestColumn
    console.log(parallelBoard)}
};

Flickering site

On reloading, the site is prickly and flickering. I think it’s because of the dark theme script. But if you write a line at the beginning, before the tag does not exist script. Then the problem disappears. But that’s not right. All showed in the video. I hope it can be resolved.

https://youtu.be/c1ab5ER4qmw

dark.js:

// function to set a given theme/color-scheme
function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
    document.getElementById("sunimgid");
}

// function to toggle between light and dark theme
function toggleTheme() {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    } else {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    }
}

// Immediately invoked function to set the theme on initial load
(function () {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    } else {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    }
})();

How to disable onclick in JavaScript?

I have been trying to do something like this.

I have a working code, (this is just example), when I click on the button the game starts.

In this example I have a loop, that if condition is true, I want to disable the option to click on the button.

I have seen that this el.disabled = true; / e.disabled = true; / td.disabled = true; (Is it possible to disable onclick without altering its function?) should do the job, but this doesn’t work for me. Why is that? Or maybe there is another way to do that? (this is not the whole code, only the important parts)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <script type="text/javascript">
    function startgame() {
      var ChessTable;
      var counter = 0;
      var center = document.createElement('center');
      ChessTable = document.createElement('table');

      for (var i = 0; i < 8; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < 8; j++) {
          var td = document.createElement('td');
          td.setAttribute('id', counter)
          td.addEventListener('click', s)
        }
        ChessTable.appendChild(tr);
      }
      center.appendChild(ChessTable);
      ChessTable.setAttribute('cellspacing', '0');
      ChessTable.setAttribute('width', '270px');
      document.body.appendChild(center);
    }

    var counterforplayer = 0;

    function s(e) {
      event.target.style.backgroundColor = "green";

      if (counterforplayer >= 5) {
        alert("you cannot play anymore")
        e.disabled = true;
        counterforplayer++;
      }
    }
    }
  </script>
  <button onclick="startgame()">Click me to start a new game</button>
  <div id="container">
    <div id="ph1">
    </div>
  </div>
</body>
</html>