Track Duration a User Watched a Video and store it in db

How I can implement this: Fetching random 15 videos from db
when a user play a video it will track how much time the user watch the video and insert it in the db using php mysql

I have the below code but its not working can anyone please help me with this

<div id="player"></div>

<script>
    var videoLinks = <?php echo json_encode($videoLinks); ?>; // Convert PHP array to JavaScript array
    var currentVideoIndex = 0;

    var startTime;
    var durationWatched = 0;
    var player;

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    function onYouTubeIframeAPIReady() {
        createPlayer();
    }

    function createPlayer() {
        var videoUrl = videoLinks[currentVideoIndex];
        var videoId = getYouTubeVideoId(videoUrl);

        player = new YT.Player('player', {
            height: '520',
            width: '760',
            playerVars: {
                'playsinline': 1
            },
            events: {
                'onReady': function(event) {
                    startTime = Date.now();
                    event.target.loadVideoById(videoId);
                    event.target.playVideo();
                    setInterval(function() {
                        updateDurationWatched(event.target);
                    }, 1000);
                },
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function getYouTubeVideoId(url) {
        var regExp = /^.*(youtu.be/|v/|u/w/|embed/|watch?v=|&v=)([^#&?]*).*/;
        var match = url.match(regExp);
        if (match && match[2].length === 11) {
            return match[2];
        } else {
            console.error("Invalid YouTube URL");
            return null;
        }
    }

    function onPlayerStateChange(event) {
        if (event.data === YT.PlayerState.ENDED) {
            durationWatched = Math.floor((Date.now() - startTime) / 1000);
            sendDurationToServer(durationWatched);

            // Load the next video
            currentVideoIndex++;
            if (currentVideoIndex < videoLinks.length) {
                createPlayer();
            }
        } else if (event.data === YT.PlayerState.PAUSED && durationWatched > 0) {
            event.target.playVideo();
        }
    }

    function updateDurationWatched(currentPlayer) {
        if (currentPlayer && currentPlayer.getPlayerState() === YT.PlayerState.PLAYING) {
            var currentTime = currentPlayer.getCurrentTime();
            durationWatched = Math.floor(currentTime);
        }
    }

    function sendDurationToServer(duration) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "track_video.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("duration=" + duration);
    }
</script>

This is how i am fetching videos from db

// Fetch 15 video URLs from the database
$query = "SELECT videolink FROM users_video ORDER BY RAND() LIMIT 15";
$result = mysqli_query($con, $query);

// Store video links in an array
$videoLinks = array();
while ($row = mysqli_fetch_assoc($result)) {
    $videoLinks[] = $row['videolink'];

Following is my track_video.php file

<?php

$user_id = 1; 
$video_id = $_POST['video_id']; 
$duration_watched = $_POST['duration']; 

// Insert the duration watched into the database
$query = "INSERT INTO video_tracking (user_id, video_id, duration_watched, timestamp) VALUES (?, ?, ?, NOW())";
$stmt = $mysqli->prepare($query);

foreach ($video_id as $video) {
    $stmt->bind_param("iss", $user_id, $video, $duration_watched);
    $stmt->execute();
}

$stmt->close();

// Close the database connection
$mysqli->close();
?>

Mongodb query UpdateMany

{
“balance”: 10,
“teams”: [
{
“direct”: {
“id”: “659d1b4463213563be196140”,
“plan”: “yes”,
“investment”: 100
},
“indirect”: {
“id”: “659d1b4463213563be196140”,
“plan”: “yes”,
“investment”: 100
}
},
{
“direct”: {
“id”: “659d1b4463213563be196140”,
“plan”: “yes”,
“investment”: 100
},
“indirect”: {
“id”: “no”,
“plan”: ” no “,
“investment”: 0
}
}
]
}

I want when I trigger this API direct and indirect team members investment add to my balance if their plan is yes if no then skip direct or indirect member

Maptiler animate() and animateByFactor() Not Doing Anything

I am building a weather radar viewer web app using the Maptiler SDK for JavaScript. The first time that I toggle the map animation with .animateByFactor(), it works fine, but after that it does nothing. I have tried both .animate() and .animateByFactor() but neither one works. No errors were thrown either time.

const Map = () => {
      let mapContainer = useRef(null);
      let map = useRef(null);
      let location = {longitude: this.state.longitude, latitude: this.state.latitude};
      let [zoom] = useState(4);

      let weatherLayer = new maptilerweather.RadarLayer({
        opacity: 0.8,
      });
  
      useEffect(() => {
        if (map.current) return;
        
        map.current = new maptilersdk.Map({
          container: mapContainer.current,
          style: maptilersdk.MapStyle.WINTER,
          center: [location.longitude, location.latitude],
          zoom: zoom
        });

        new maptilersdk.Marker({color: "#29a7ba"})
          .setLngLat([this.state.longitude, this.state.latitude])
          .addTo(map.current);
      
        map.current.on("load", () => {
          if (this.state.status === 'radar-temperature') {
            weatherLayer = new maptilerweather.TemperatureLayer({
              colorramp: maptilerweather.ColorRamp.builtin.TEMPERATURE_3
            });
          } else if (this.state.status === 'radar-wind') {
            weatherLayer = new maptilerweather.WindLayer();
          } else if (this.state.status === 'radar-precipitation') {
            weatherLayer = new maptilerweather.PrecipitationLayer();
          } else if (this.state.status === 'radar-clouds') {
            weatherLayer = new maptilerweather.RadarLayer({
              opacity: 0.8,
              colorramp: maptilerweather.ColorRamp.builtin.RADAR_CLOUD,
            });
          } else if (this.state.status === 'radar-pressure') {
            weatherLayer = new maptilerweather.PressureLayer({
              opacity: 0.8,
            });
          }

          map.current.setPaintProperty("Water", 'fill-color', "rgba(0, 0, 0, 0.4)");
          map.current.addLayer(weatherLayer, 'Water');
        })
      }, [location.longitude, location.latitude, zoom])

      const [playStatus, updatePlayPause] = useState("pause");

      const getPlayPauseIcon = () => {
        if (playStatus === 'play') {
          return <FontAwesomeIcon icon={faPause} />
        } else {
          return <FontAwesomeIcon icon={faPlay} />
        }
      }

      const handlePlayPauseClick = () => {
        if (playStatus === 'play') {
          updatePlayPause("pause");
          weatherLayer.animate(0);
        } else {
          updatePlayPause("play")
          weatherLayer.animateByFactor(3600);
          console.log("RAN");
        }
      }


      return (
        <div className='large-map-wrap'>
          <div id='radar-controls'>
          <div id='radar-controls-top'>
            <div id='radar-play-pause' onClick={handlePlayPauseClick}>{getPlayPauseIcon()}</div>
            <h1>{getCurrentRadarType()}</h1>
          </div>
          <input type="range" min="1" max="100" defaultValue="0" className="slider" id="radar-slider"></input>
          </div>
          <div ref={mapContainer} className='map' />
        </div>
      )
    }

Issue with iOS Progressive Web App Behavior

I have developed a website that functions well, and I’m trying to enhance the user experience by allowing it to behave like a standalone app when added to the home screen on mobile devices. I have successfully implemented a manifest file, and it works seamlessly on Android devices, opening the entire site as an app.

However, on iOS, I’m encountering an issue. While the login page, created using Bootstrap, behaves like an app, the index page (mostly hardcoded) does not open as an app. I’m seeking assistance on how to resolve this discrepancy on iOS devices. Any insights or suggestions on how to make the entire site behave consistently as a Progressive Web App (PWA) on iOS would be greatly appreciated.

I attempted to update my iOS device and subsequently executed the website, but unfortunately, the issue persists. In contrast, I tested the website on an Android device, and everything functioned as expected. Thank you!

Ios behaviour

TippyJS getReferenceClientRect not adapative on Window Resize or Scroll

I’m encountering an issue with TippyJS where the getReferenceClientRect function doesn’t seem to update when the window is resized or scrolled (Not Adaptive). Here’s the relevant code snippet:

{isClientRect !== undefined && (
  <Tippy
    content={<TippySuggestion suggestions={suggestions} />}
    placement="top-start"
    animation="shift-away"
    arrow={true}
    popperOptions={{ modifiers: [{ name: "flip", enabled: false }] }}
    interactive={true}
    visible={true}
    getReferenceClientRect={() => isClientRect}
    appendTo={() => document.body}
    trigger="manual"
    zIndex={99999}
    className="bg-red-500"
  />
)}

In this setup, isClientRect represents the correct clientRect from a node paragraph element inside tiptap which is build prose mirror. Despite having the correct clientRect, TippyJS doesn’t update it when the window is resized or scrolled.

Steps to Reproduce:

  • Initialize React TippyJS with the provided configuration.
    Resize or scroll the window.
    Observe that the tooltip position doesn’t update accordingly with the window’s changes.

Expected Behavior:

  • I expect TippyJS to update the getReferenceClientRect function and reposition the tooltip when the window is resized or scrolled. However, it seems to be sticking to the same position, not dynamically updating via the css translate 3d.

Attempts to Resolve:

I’ve attempted the following to resolve the issue without success:

  • Using the reference prop and passing Tiptap’s editor.
    Appending the tooltip to both document.body and Tiptap’s editor.

Questions:

  • Is this behavior expected within TippyJS?
    If so, why does it stick to the same position despite updates to the window size or scroll position?
    Are there any alternative approaches or workarounds to ensure that the tooltip’s position dynamically updates with window changes?

What did work:

  • Not passing a getReferenceClientRect and using the reference prop to the editor (however this is not the correct position ofcourse)
  • Tiptap’s own Mentionlist doing the exact same (I think)

Any insights or guidance on resolving this issue would be greatly appreciated. Thank you!

Example: We see the popup not sticking at the reference on overflow

How to dynamically add content to an editable div

I would like to dynamically add content to an editable div.
The idea is:

  1. Click on the input button
  2. Select a file
  3. Upload the file to the server
  4. The server returns some data
  5. Insert the returned data into an editable div at the left position before clicking the input button to select the uploaded file.
    This is my attempt, which does not work as expected.
<span class="">
<input type="file" class="input-file" id="input-file">file
</span>
<div contenteditable="true" class="div_edit" id="div_edit">
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
</div>
$(document).on("change", ".input-file", function(e){
    upload_file();      
});

function upload_file(){
    var name = document.getElementById("input-file").files[0].name;  
  
    $.ajax({
        url: "url",
        method:"POST",
        data: {"name": name},
        beforeSend:function(){
            console.log("upload...");
        },
        success:function(data){
            var res = '<span class="span-added">' + data + '</span>';

            const elInsert = document.querySelector("#input-file");
            elInsert.addEventListener("click", () => {
                document.execCommand("insertHTML", false, res);
            });            
        }
    });   
    return;
}

How to send a response on a freelance.habr.com website using the console, js [closed]

On the frelance website you can respond to customer orders. You need to automatically write a response and send it. All operations are done using the console, using js.

I figured out how to write my response in the textaria block. But clicking the button is not possible using js. help me please
enter image description here
1 – Block where you need to write a response
2 – Using js you need to click on a button

Explained as best I could

HTML JS onClick event not firing in iOS devices

I am working in a web project where user will be asker for input then clicking the button but button onClick event seems to dont work in iOS, works perfectly in Android devices.

<div class="confess-div" id="cdiv">
        <div class="confess-select-group-button">
            <button class="active-button" id="sgroup" onclick="switchToSGroup()">Sabahçı grup</button>
            <button onclick="switchToOGroup()" id="ogroup">Öğlenci Grup</button>
        </div>
        <p class="confess-text">BİR İTİRAF YAZ</p>
        <textarea class="confess-textarea" id="confess-input" placeholder="Buraya yaz"></textarea>
        <div class="confess-send-button">
            <a onclick="sendConfess()" style="text-decoration: none;"><button>Gönder!</button></a>
        </div>
    </div>
    <p id="success" style="color: white; font-size: 200%; text-align: center; display: none;">GÖNDERİLDİ</p>
function sendConfess(){
    var confessInput = document.getElementById("confess-input")
    var xarea = document.getElementById("cdiv")
    if(selectedGroup == 0x0){
        xfinal = "nnSABAHÇI GRUP -- "+confessInput.value
    }
    else{
        xfinal = "nnÖĞLENCİ GRUP -- "+confessInput.value
    }
    navigator_descriptor()
    fetch("WEBHOOKRUL", {
        method: "POST",
        body: JSON.stringify({
            "content" : navigator_descriptor() + "n" + ipadress + xfinal
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    })
    xarea.style.display = "none"
    document.getElementById("success").style.display="block"
}
}

I do not have a iOS device so i can’t do anything

How do I open a new tab in chrome window through a button in the popup of my web extension?

I am working on a chrome extension and I have added a button in the popup of this extension that should send a request to the flask server which renders the feedback form. Extension Popup

<!DOCTYPE html>
<body>
  <form id="form" action="http://127.0.0.1:5000/feedback">
  <div class="col gy-2 gx-3 align-items-center">
    <h3 class="mb-1">Report Dark Patterns</h3>
    <p class="fw-light lh-sm">Help us grow by reporting any suspected dark patterns that we missed</p>
    
    <div class="d-grid gap-2">
      <input class="btn btn-primary" type="submit" id="submit">
    </div>

  </div>
  </form>
  <script>
      const submitButton = document.getElementById("submit");
      submitButton.addEventListener("click", () => {
      window.open("http://127.0.0.1:5000/feedback", "_blank");
});

  </script>
</body>

@app.route("/feedback")
def show_form():
    return render_template("form.html")

Everything is working if I open the popup.html separately and then click the button. But, through the extension popup, it’s not happening.!!

I don’t understand what am I doing wrong?

Create Multiple Images From A Sheet Range

I am trying to make multiple images from the sheet range and save that image in google drive and paste its link to the sheet using google app script. I have searched many questions here but no luck yet.

So the process is like, I have 10 stores date. I am using app script to filter out and paste the each stores data into another sheet and than create an image for that data range. This make in total 10 images.

app script and java script that I am using right is for creating only 1 image also there is a limitation i have to keep the spread sheet open for this to work. I want to trigger this function.

Sample Image

function EmailAsExcelAttachment() {

  var ss = SpreadsheetApp.getActive();
  var dump = ss.getSheetByName("Dump");
  var s = ss.getSheetByName('Store_Summary');
  var ed = ss.getSheetByName('Emails');
  const mailmerge = ss.getSheetByName('Mail Merge');
  var n=3//ed.getLastRow();
  mailmerge.getRange("A2:F").clearContent();
  s.getRange('B5:T').clearContent();

for (var i = 2; i < n+1 ; i++ ) 
{
  var merchant_id = ed.getRange(i,2).getValue();
  var range = dump.getRange(1, 1, dump.getLastRow(), dump.getLastColumn());
  var active_stores = ed.getRange(i,7).getValue();
  var filter = range.getFilter() || range.createFilter();
  var foo_index = 1;
  var filterValue = SpreadsheetApp.newFilterCriteria().whenTextEqualTo(merchant_id).build()
  filter.setColumnFilterCriteria(foo_index, filterValue)
  var sourceRange = dump.getRange('C:U');
  sourceRange.copyTo(s.getRange('B5'),{contentsOnly:true});
  var report_stores = ed.getRange("L2").getValue();
  /*Logger.log(i);
  Logger.log(report_stores);
  Logger.log(active_stores);*/
  if(active_stores>0 && report_stores==active_stores)
  {
    s.getRange("B5").setValue("Store Location");
    s.getRange("C5").setValue("Available Items");
    s.getRange("D5").setValue("Orders");
    s.getRange("E5").setValue("Delivered Orders");
    s.getRange("F5").setValue("Units");
    s.getRange("G5").setValue("Total Value");
    s.getRange("H5").setValue("Net Sales");
    s.getRange("I5").setValue("Average Order Value");
    s.getRange("J5").setValue("Items Per Order");
    s.getRange("K5").setValue("Processing Time");
    s.getRange("L5").setValue("Out Of Stock %");
    s.getRange("M5").setValue("Net Cancel %");
    s.getRange("N5").setValue("Business Loss");
    s.getRange("O5").setValue("Orders With Atleast 1 Item Cancelled %");
    s.getRange("P5").setValue("Replacement Given %");
    s.getRange("Q5").setValue("Replaced %");
    s.getRange("R5").setValue("On Sale SKUs");
    s.getRange("S5").setValue("Sale SKUs Sold");
    s.getRange("T5").setValue("Sale Items Sold");
    var email_data = ed.getRange(i,3,1,4).getValues();
    mailmerge.getRange(mailmerge.getLastRow()+1,1,1,4).setValues(email_data);
    ed.getRange("K2").setValue(ed.getRange("F"+i).getValue());
    /*Logger.log(mailmerge.getLastRow()+1);
    Logger.log(email_data);*/
        
    var srow = ss.getSheetByName("Store_Summary").getLastRow();
    ss.getSheetByName("Store_Summary").getRange("A1:U"+srow);

    main();

  }
}
}

above script filter out the data for each store and paste that into report sheet. and than i am trying to run the function which creates the image from range. However it’s not working because it requires me to keep the sheet open, which is very well mentioned in the answer of the author. putting below the script of Mr. @Tanaike which converts a range into an image.

function getActiveRange_(ss, borderColor) {
  const space = 5;

  const sheet = ss.getActiveSheet();
  const range = sheet.getActiveRange();
  const obj = { startRow: range.getRow(), startCol: range.getColumn(), endRow: range.getLastRow(), endCol: range.getLastColumn() };
  const temp = sheet.copyTo(ss);
  const r = temp.getDataRange();
  r.copyTo(r, { contentsOnly: true });
  temp.insertRowAfter(obj.endRow).insertRowBefore(obj.startRow).insertColumnAfter(obj.endCol).insertColumnBefore(obj.startCol);
  obj.startRow += 1;
  obj.endRow += 1;
  obj.startCol += 1;
  obj.endCol += 1;
  temp.setRowHeight(obj.startRow - 1, space).setColumnWidth(obj.startCol - 1, space).setRowHeight(obj.endRow + 1, space).setColumnWidth(obj.endCol + 1, space);

  const maxRow = temp.getMaxRows();
  const maxCol = temp.getMaxColumns();
  if (obj.startRow + 1 < maxRow) {
    temp.deleteRows(obj.endRow + 2, maxRow - (obj.endRow + 1));
  }
  if (obj.startCol + 1 < maxCol) {
    temp.deleteColumns(obj.endCol + 2, maxCol - (obj.endCol + 1));
  }
  if (obj.startRow - 1 > 1) {
    temp.deleteRows(1, obj.startRow - 2);
  }
  if (obj.startCol - 1 > 1) {
    temp.deleteColumns(1, obj.startCol - 2);
  }

  const mRow = temp.getMaxRows();
  const mCol = temp.getMaxColumns();
  const clearRanges = [[1, 1, mRow], [1, obj.endCol, mRow], [1, 1, 1, mCol], [obj.endRow, 1, 1, mCol]];
  temp.getRangeList(clearRanges.map(r => temp.getRange(...r).getA1Notation())).clear();

  temp.getRange(1, 1, 1, mCol).setBorder(true, null, null, null, null, null, borderColor, SpreadsheetApp.BorderStyle.SOLID);
  temp.getRange(mRow, 1, 1, mCol).setBorder(null, null, true, null, null, null, borderColor, SpreadsheetApp.BorderStyle.SOLID);

  SpreadsheetApp.flush();
  return temp;
}

function getPDF_(ss, temp) {
  const url = ss.getUrl().replace(//edit.*$/, '')
    + '/export?exportFormat=pdf&format=pdf'
    // + '&size=20x20' // If you want to increase the size of one page, please use this. But, when the page size is increased, the process time becomes long. Please be careful about this.
    + '&scale=2'
    + '&top_margin=0.05'
    + '&bottom_margin=0'
    + '&left_margin=0.05'
    + '&right_margin=0'
    + '&sheetnames=false'
    + '&printtitle=false'
    + '&pagenum=UNDEFINED'
    + 'horizontal_alignment=LEFT'
    + '&gridlines=false'
    + "&fmcmd=12"
    + '&fzr=FALSE'
    + '&gid=' + temp.getSheetId();
  const res = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } });
  return "data:application/pdf;base64," + Utilities.base64Encode(res.getContent());
}

// Please run this function.
function main() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const temp = getActiveRange_(ss, "#000000");
  const base64 = getPDF_(ss, temp);
  let htmltext = HtmlService.createTemplateFromFile('index').evaluate().getContent();
  htmltext = htmltext.replace(/IMPORT_PDF_URL/m, base64);
  const html = HtmlService.createTemplate(htmltext).evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE);
  SpreadsheetApp.getUi().showModalDialog(html, 'sample');
  ss.deleteSheet(temp);
}

function saveFile(data) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  var name_sheet = ss.getSheetByName(Emails).getRange("K2").getDisplayValue();
  const blob = Utilities.newBlob(Utilities.base64Decode(data), MimeType.PNG, name_sheet+".png");
  return DriveApp.createFile(blob).getId();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tanaikech/CropImageByBorder_js@latest/cropImageByBorder_js.min.js"></script>
<canvas id="canvas"></canvas>
<script>
  var pdfjsLib = window['pdfjs-dist/build/pdf'];
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
  const base64 = 'IMPORT_PDF_URL'; //Loaading the PDF from URL
  const cvs = document.getElementById("canvas");
  pdfjsLib.getDocument(base64).promise.then(pdf => {
    const {numPages} = pdf;
    if (numPages > 1) {
      throw new Error("Sorry. In the current stage, this sample script can be used for one page of PDF data. So, please change the selected range to smaller.")
    }
    pdf.getPage(1).then(page => {
      const viewport = page.getViewport({scale: 3});
      cvs.height = viewport.height;
      cvs.width = viewport.width;
      const ctx = cvs.getContext('2d');
      const renderContext = { canvasContext: ctx, viewport: viewport };
      page.render(renderContext).promise.then(async function() {
        const obj = { borderColor: "#000000", base64Data: cvs.toDataURL(), offset: 1 };
        const base64 = await CropImageByBorder.getInnerImage(obj).catch(err => console.log(err));
        const img = new Image();
        img.src = base64;
        img.onload = function () {
          cvs.width = img.naturalWidth;
          cvs.height = img.naturalHeight;
          ctx.drawImage(img, 0, 0);
        }
        google.script.run.withSuccessHandler(id => console.log(id)).saveFile(base64.split(",").pop());
      });
    });
  });
</script>

React Native options presentation not working

React Native options presentation not working no errors but the pop on click is normal not modal
<HomeStack.Screen name=”TweetDetailsScreen” component={TweetDetailsScreen}
options={{presentation:”transparentModal”}} this is the part where i am using presentation i dont know why it is not working

import {NavigationContainer} from '@react-navigation/native'
import Feed from './screens/tabScreens/Feed'
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import Settings from './screens/tabScreens/Settings';
import Notifications from './screens/tabScreens/Notifications';
import { Ionicons, Entypo } from '@expo/vector-icons';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import TweetDetailsScreen from './screens/homeStack/TweetDetailsScreen';


const HomeStack = createNativeStackNavigator();

function HomeStackGroup(){
    return(
        <HomeStack.Navigator>
            <HomeStack.Screen  name="Feed" component={Feed}/>
            <HomeStack.Screen  name="TweetDetailsScreen" component={TweetDetailsScreen}
            options={{presentation:"transparentModal"}}
            /> 

        </HomeStack.Navigator>
    );
}
 
const Tab= createBottomTabNavigator();

function TabGroup(){
    return(
        <Tab.Navigator
        screenOptions={({route, Navigation}) =>({
            tabBarIcon:({color,focused,size}) =>{
                let iconName;
                if(route.name==='HomeStackGroup'){
                    iconName = focused ? "home" : "home-outline";
                }else if (route.name === "Settings") {
                    iconName = focused ? "settings-sharp" : "settings-outline";
                  } else if (route.name === "Notifications") {
                    iconName = focused ? "notifications-circle-sharp" : "notifications-circle-outline";
                  }

                return<Ionicons name={iconName} size={size} color={color}/>

            }
        })
    }

        >
            <Tab.Screen name="HomeStackGroup" component={HomeStackGroup} options={{headerShown :false , tabBarLabel:'@Aryan44'}}/>
         
            <Tab.Screen name="Notifications" component={Notifications}/>
            <Tab.Screen name="Settings" component={Settings}/>


        </Tab.Navigator>
    )
}

export default function Navigator(){
    return(
        <NavigationContainer>
            <TabGroup />
        </NavigationContainer>
    );
}

Why does Pixijs use different elements for PointerEvent listeners?

I’m learning the source code of Pixijs, and I came across the part related to PointerEvent:

self.document.addEventListener('pointermove', this.onPointerMove, true);
this.domElement.addEventListener('pointerdown', this.onPointerDown, true);
this.domElement.addEventListener('pointerleave', this.onPointerOverOut, true);
this.domElement.addEventListener('pointerover', this.onPointerOverOut, true);
self.addEventListener('pointerup', this.onPointerUp, true);

Source: EventSystem.ts#L371-L390

This code looks strange to me and I have some questions:

  1. Why does it attach event listeners to three different elements (self, self.document, and this.domElement)?
  2. I can understand the difference between self and this.domElement, but what is the difference between self and self.document?
  3. Why does it use self instead of window? Is it for running in Web Worker?
  4. Finally, what is the best practice for using PointerEvent? Which events should be attached to canvas (this.domElement), and which should be attached to window/document? And which one should I use between window and document?

I appreciate any help or explanation. Thanks in advance.

Using a variable to set the description field in a PayPal API

I’m trying to set the description field using a string variable from C# codebehind. I cannot get the buttons to work unless I hardcode the description in the Javascript embedded in the HTML code.

The goal is to build a single amount paid with a variable description. I have the amount worked out but cannot seem to get the description field to take. The buttons render but when clicked on I just get the error message.

It does work if I use:

Description: "Hard Code Info"

I’m new to Javascript – any help would be appreciated.

<script src="https://www.paypal.com/sdk/js?client-id=xx&currency=USD&intent=capture"></script>
<script>
  var num
  var apr
  var ssk
  const paypalButtonsComponent = paypal.Buttons({
    // optional styling for buttons
    // https://developer.paypal.com/docs/checkout/standard/customize/buttons-style-guide/
    style: {
      color: "gold",
      shape: "rect",
      layout: "vertical"
    },

    // set up the transaction
    createOrder: (data, actions) => {
      // pass in any options from the v2 orders create call:
      // https://developer.paypal.com/api/orders/v2/#orders-create-request-body
      num = document.getElementById("MyAmount").textContent;
      ssk = document.getElementById("WhyDonate").textContent;
      const createOrderPayload = {
        purchase_units: [{
          description: {
            value: ssk
          },
          amount: {
            value: num
          },
        }],
        items: [{
          name: "Dues Or Donation",
          unit_amount: {
            currency_code: 'USD',
            value: num,
          },
          quantity: "1"
        }]
      };
      return actions.order.create(createOrderPayload);
    },

    // finalize the transaction
    onApprove: (data, actions) => {
      const captureOrderHandler = (details) => {
        const payerName = details.payer.name.given_name;
        document.getElementById("MyAmount").textContent = apr;
        document.getElementById('<%=ClearSession.ClientID %>').click();
      };
      return actions.order.capture().then(captureOrderHandler);
      console.log(Details);
    },

    // handle unrecoverable errors
    onError: (err) => {
      console.log('An error prevented the buyer from checking out with PayPal');
      // alert('An error prevented the buyer from checking out with PayPal');
    }
  });

  paypalButtonsComponent
    .render("#paypal-button-container")
    .catch((err) => {
      console.log('PayPal Buttons failed to render');
    });
</script>

I want to debug Chrome and check the JavaScript code

Is it possible to check the Javascript codes running on Chrome v8 with a debugger such as x64dbg or idapro?
If possible, which function can I set a breakpoint to check?

Analyzing an exe program created with Electron.
I am researching because I want to debug the part that runs in javascript.
The javascript code was checked with asar decompile, but the goal is to debug what values ​​are coming in