How to append query parameters to an URL using Chrome Extension’s declarativeNetRequest API

I want to develop a chrome extension that allows to append a query parameter to a specific URL (i.e. from www.google.com to www.google.com?q=query).

In Manifest v2 it was possible to accomplish it by using the webRequest API, but in Manifest v3 the API has been replaced by declarativeNetRequest. How is it possible to replicate the Manifest v2 solution in v3 through the declarativeNetRequest?

The ideal scenario would be even the possibility to specify the website domain through an input field in an extension’s popup.

Thanks

Configuring a forked process entry point with Electron-Builder

I am using [email protected] and am forking a process to run in the background, which works correctly running npm run dev and npm run start.

e.g.

const childPath = app.isPackaged
  ? path.join(process.resourcesPath, './src/main/child.js')
  : path.join(__dirname, '../../src/main/child.js')

const child = fork(childPath, ['initialize'], { 
  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
})

The child.js file also has two node_module dependencies that I have included in the asarUnpack section of my electron-builder.yml file

asarUnpack:
  - '**/*.{node.dll}'
  - '**/node_modules/dependency_1'
  - '**/node_modules/dependency_2'

The issues I am having are:

  • I am able to access the child.js file if I move it to a root level folder and add that to extraResources – but in that case it does not seem to be able to access its node_module dependencies.
  • If I move it into the main application folder, as shown above, then I don’t seem to be able to get electron-builder to copy the child.js file into out/main. I have tried including from/to definitions in files and extraResources

Can someone point me in the right direction or to a functional example somewhere?

I am expecting to be able to package the application with the child.js application available to be called (like in the code above) in a manner in which it will have access to its node_module dependencies, despite being outside of the build lifecycle dependencies of main, preload and renderer targets.

I have tried the examples defined and approaches defined above.

Updating a form’s select element’s selectedIndex property, updates the value, but doesn’t change the selected option in the page

Here is the code:

const formClubSelect: HTMLSelectElement | null = document.getElementsByTagName('select',)[1] as HTMLSelectElement;
if (formClubSelect) {
    for (var i = 0; i < formClubSelect.options.length; i++) {
        const option = formClubSelect.options[i];

        if (option.value === clubId && option.text === clubName) {
            formClubSelect.selectedIndex = option.index;
            formClubSelect.options[option.index].selected = true;
        }
    }
}

The option’s can sometimes have the same value, so I’m looping through them and checking the value/text based on some previous values. If the values match the option ones, I try to set the index on the select element, as well as set the selected property on the option to true. I’ve tried setting just the option selected property, but it doesn’t seem to change anything.

I’ve also checked the index before and after the change and it does update, but the option doesn’t appear on the select:

enter image description here

HTML Datalist won’t restrict to 5 or x items

I tried to no avail to get HTML, CSS and Javascript to limit number of items in datalist, for whatever reason, it is isn’t working. The list is populated by a loop on a array.

<datalist id="trainNoList">
 <script>
if (markers)
{
  var options = '';
  var trainNoList = [];
  

  for (var i = 0; i < markers.length; i++) {
    var trainNo = markers[i][20];
    trainNoList.push(trainNo);
    options += "<option value='" + trainNoList[i] + "'></option>";
  }

}
</script>
</datalist>

<!-- Use JavaScript to pan to the train when an option is selected -->

<script>
  $("#trainNoInput").on("input", function() {
    var selectedTrainNo = $(this).val();
    
    // Check if the input is a range
    var rangeCheck = selectedTrainNo.split("-");
    if (rangeCheck.length === 2) {
      vehiclestart = rangeCheck[0];
      vehicleend = rangeCheck[1];
      
    } else {
      // Perform the same actions as in the original code
      for (var i = 0; i < markers.length; i++) {
        var trainNo = markers[i][20]; 
        if (trainNo == selectedTrainNo) {
          var lat = parseFloat(markers[i][2]);
          var lng = parseFloat(markers[i][3]);
          var setcontentforpopup = "Vehicle"+markers[i][0]+"";
            vehiclestart = 1;
      vehicleend = 99999999999999;
          var popup = L.popup()
            .setLatLng([lat, lng])
            .setContent(setcontentforpopup)
            .addTo(map);
          map.flyTo([lat, lng], 16);
          break;
        }
      }
    }
  });
  
$("#trainNoInput").on("focus", function() {
    console.debug("The trainNoInput field has received a keyup event");
clearTimeout(ajaxtimeout);
});

$("#trainNoInput").on("blur", function() {
ajaxtimeout = setTimeout(foo, 10000);
console.debug("no");
});

$("#trainNoInput").on("keyup", function(event) {
if (event.keyCode === 13) {
    markerLookup = {};
     markerClusters.clearLayers();
foo();
}
});


</script>

enter image description here

The desire result is simple – limit number of items shown down to 5 or whatever set amount

enter image description here

I do not understand about bitwise operator in Javascript

I am student studying programming.

As far as I know, Javascript saves number as float.

However, bitwise operator in Javascript run as a type of number is integer.

For instance,

> 1 | 2 // -> 3
> 2 << 4 // -> 32

How is it possible?

I find official documentation(mdn web docs), but I can not find the reason.

In functional programming, how to convert a function which uses global variables into a pure function? [duplicate]

In the code below, power isn’t a pure function (uses two global variables), how can i convert it into a pure function with just one input array as parameter?

const multiplyByFour = function (array) {
  return array.map((item) => item * 4);
};

const sumElements = function (array) {
  return array.reduce((total, num) => {
    return total + num;
  });
};

function power(arr) {
  let lengthArray = arr.length;
  let value = sumElements(multiplyByFour(arr));
  return Math.pow(value, lengthArray);
}

console.log(power([3, 4, 2]));

Reload/Refresh a Clickable Button

I’m making a Project. Where as there is a feature that I needed a Clickable Button to be Refresh. Like exactly the button to be refresh.

How can I implement this? Is this possible?

My idea of doing this is by using “document.location.replace(“id of button”)”

Thank you, Beginner Here…

How can I draw a single cycle waveform (triangle,saw,) using JS (with phase control)?

I’m trying to generate a single cycle of a waveform, but which can be modified by a phase control. So far I managed to figure out a sine wave like this –

m.move_to(x,y);
for(var i = -w; i < w * 2; i++) {
            
    y = amp * h * 0.5 * Math.sin((i + (phase + 0.5) * w) * ((Math.PI * 2) / w)) + h * 0.5;
            
    m.line_to(x + i,y);
        
}

This is using mgraphics inside max/msp, but it should be clear, just simple code. w and h are the width and height of the box. I started the loop with -w to avoid a line at the start going from the origin x=0,y=0.5 * h.

I tried following the basic logic of this post in order to implement a triangle wave but it ends up starting and ending at y=1, and it doesn’t loop, so when I change the phase I just end up with a lot of blank space.

This is what I have so far for the triangle inside the loop –

y = amp * h * 0.5 * (1 - Math.abs((i + (phase) * w) / w - 0.5) * 4) + h * 0.5;

window.innerHeight odd behavior on chrome mobile

I tested this odd behavior on new Pixel 7 Pro(Android 13) using chrome browser(110.0.5481.63).

Test:

I created a simple app that prints out window,innerWidth and window.innerHeight to the screen. I also experienced this behavior using this webpage (https://www.rapidtables.com/web/tools/window-size.html), (Disclaimer: not hosted by me)

on initial load without any user interaction when i enter the address and visit the site using Mobile Chrome on Android device (Pixel 7pro) the dimensions are 412×1101.

window inner dimensions on initial load without any user interaction

on interaction(tap or click refresh) it is 412 x 775

window inner dimensions son tap or click

and upon scroll as expected the address bar hides and the dimensions are 412 x 831.

window inner dimensions after scroll

Issue: Why is the initial height 1101 ? I would expect it to be 775 and on scroll when the address bar hides to be 831

Carousel is not hidden on load, even though it must be

I would greatly appreciate if somebody will help me.

Si I am trying to make a web page with 3 tabs “London, New York, Shanghai”.
On load all is hidden, only “welcome” page is visible.

I Implemented a carousel for images for “London” and it works as intended, but when I tried to copy-and-paste js code for the page and rename all variables for New York, it worked but now
New York Carousel is in display:block for some reason, when it has to be in display:none by default (in CSS).

And this New Work carousel is on other pages as well.

It has tailwind in it as well but I don’t think the problem is in it.

https://github.com/Nikita0x/Nikita0x.github.io/tree/main/cities

I have checked everything meticulously, there should not be any typos, unclosed tags and all cases match. I can’t wrap my mind around it, i was trying to copy this – https://www.w3schools.com/howto/howto_js_slideshow.asp

but it is as if .mySlides_ny {display:none} is ignored

How To Stop API Request From Looping In The Network Tab

So, currently, i’m working with an API that gets a list of accounts and each account can be deleted. So, In my code, I called the function to get all accounts in a useEFfect passing in the account details stateThis is a screen shot of my code as a dependency. If i now go to my browser and check the network tab I noticed the frequent request of the endpoint That is a screen shot of the loop in the network tab. Please I want to know why that is happening and how it can be solved.

There is a screen shot of what I tried

Indentation in vscode

I have the code below:


const arr = [...];

const someResult = arr.map(value => ({
  props1: value.props1,
  props2: value.props2
})

is there any way to make the code formatting look like this in vscode?

const someResult = arr
  .map(value => ({
    props1: value.props1,
    props2: value.props2
  })

Transfer animation code (script) to external file

I made the animation code which works correctly, but when I move this code to an external file, the code doesn’t work.

$(document).ready( function() {
            var item_width = $('#slides li').outerWidth(true);
            var old_left = parseInt($('#slides ul').css('left'));
            var top_indent = old_left - item_width;
            var right_indent = item_width + old_left;
            var left = 0;

            var animateBox = function () {
                left = (left) ? 0 : (right_indent / 3);

                $('#slides ul').animate({
                    'top': top_indent,
                    'left': left

                }, 1500, function () {
                    $('#slides li:last').after($('#slides li:first'));
                    $('#slides ul').css({ 'top': 0 });
                    setTimeout(function () { animateBox(); }, 0);
                });
            }
            animateBox();
        });

I tried this too but it still didn’t work.

$(function () {

       // code

        });

Quote Web API (XMLHttpRequest)

I keep receiving a syntax error in the test responseReceivedHandler(). Line 19, column 26: SyntaxError: Unexpected token u in JSON at position 0

The fetchQuotes() function in quote.js is called with the selected topic and count when the Fetch Quotes button is clicked. Currently, fetchQuotes() displays example quotes in an ordered list inside the <div> with ID quotes.

Modify fetchQuotes() to use the XMLHttpRequest object to request quotes from the quote web API. Set the XMLHttpRequest‘s responseType to expect a JSON response.

Create a new function called responseReceivedHandler() that receives the XMLHttpRequest response and displays the quotes in an ordered list. Each quote should be followed by a space, a dash, a space, and the source.

Ex: If the user chooses “love” and “3” and presses Fetch Quotes, responseReceivedHandler() should place the returned quotes in an ordered list inside the <div>:

<div id="quotes">
   <ol>
      <li>If I know what love is, it is because of you. - Hermann Hesse</li>
      <li>The opposite of love is not hate, it's indifference. - Elie Wiesel</li>
      <li>Suffering passes, while love is eternal. - Laura Ingalls Wilder</li>
   </ol>
"use strict";
window.addEventListener("DOMContentLoaded", function () {
   document.querySelector("#fetchQuotesBtn").addEventListener("click", function () {

      // Get values from drop-downs
      const topicDropdown = document.querySelector("#topicSelection");
      const selectedTopic = topicDropdown.options[topicDropdown.selectedIndex].value;
      const countDropdown = document.querySelector("#countSelection");
      const selectedCount = countDropdown.options[countDropdown.selectedIndex].value;
   
      // Get and display quotes
      fetchQuotes(selectedTopic, selectedCount);       
   });
});

function fetchQuotes(topic, count) {
   const xhr = new XMLHttpRequest();
   xhr.open("GET", `https://wp.zybooks.com/quotes.php?topic=${topic}&count=${count}`);
   xhr.responseType = "json";
   xhr.addEventListener("load", responseReceivedHandler);
   xhr.send();
}

function responseReceivedHandler() {
   const response = JSON.parse(this.responseText);
   console.log(response); // log the response to the console
   let html = "";
   if (response.error) {
      html = response.error;
   } else {
      html = "<ol>";
      response.quotes.forEach(function (quote) {
         html += `<li>${quote.quote} - ${quote.source}</li>`;
      });
      html += "</ol>";
   }
   document.querySelector("#quotes").innerHTML = html;
}