Native messaging On edge Browser

{
  "manifest_version": 3,
  "name": "Mac Address",
  "version": "1.0",
  "description": "Mac Address",
  "permissions": [
    "activeTab",
    "nativeMessaging", 
    "tabs"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["url of product"],
      "js": ["content.js"]
    }
  ],
  "host_permissions": [
    "url of product"  
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}


the code is manifest.json

const nativeHostName = 'com.example.macaddress';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "sendToNativeHost") {
    console.log("Sending message to native host:", request.data);
    chrome.runtime.sendNativeMessage(nativeHostName, request.data, (response) => {
      if (chrome.runtime.lastError) {
        console.error("Native message error:", chrome.runtime.lastError.message);
        sendResponse({ success: false, error: chrome.runtime.lastError.message });
      } else {
        console.log("Received response from native host:", response);
        sendResponse({ success: true, response });
      }
    });
    return true; // Indicates that the response will be sent asynchronously
  }
});

the above code is background.js

function monitorAndHandleClick() {
  const targetElement = document.querySelector('label#lblLogin.mybutton.btnPadding');

  if (targetElement) {
    console.log("Target element found:", targetElement);
    targetElement.addEventListener('click', () => {
      const dataToSend = {
        action: "sendToNativeHost",
        data: {
          url: window.location.href,
          elementId: targetElement.id,
          timestamp: new Date().toISOString()
        }
      };
      console.log("Sending message to background script:", dataToSend);
      chrome.runtime.sendMessage(dataToSend, (response) => {
        if (response && response.success) {
          console.log("Message sent to native host successfully.");
        } else {
          console.error("Failed to send message to native host:", response);
        }
      });
    });
  } else {
    console.error("Target element not found.");
  }
}

if (window.location.href === 'url of product') {
  console.log("Target URL matched, starting click monitoring.");
  monitorAndHandleClick();
}

the above code content.js .

All above code is working fine on chrome browser(131.0.6778.205) but not on edge (131.0.2903.112). can i now where the mistake is? and i have reg on registry in path of

ComputerHKEY_LOCAL_MACHINESOFTWAREMicrosoftEdgeNativeMessagingHostscom.example.macaddress .

when the Above code is Working fine on chrome browser but not on Edge can i Know where the problem is?

Chess.js loads custom fen but falls back to default fen on moving through pgn that causes game break

Sorry this might be a very nooby question.

I am building a chess pgn database for someone and I am stuck at the finish line.

I have everything working (when a standard chess Forsyth–Edwards Notation (FEN) is loaded in)

Whenever I load a custom fen from the database, it loads the fen fine, but when you press on next btn it falls back to the default fen.

Please tell me what I can do to resolve this issue.

ChatGPT does not know either

window.loadPGN = function(id) {
  $.getJSON('php/get_pgn.php?id=' + id, function(data) {
    if (data.success) {
      const startingFen = data.starting_fen || 'start';

      // Initialize the chessboard with the starting FEN
      board = ChessBoard('annotation-board', {
        pieceTheme: cfg.pieceTheme,
        position: startingFen,
      });

      // Initialize the Chess.js game object with the starting FEN
      game = new Chess(startingFen);

      // Load the PGN into the Chess.js game instance
      game.load_pgn(data.pgn_data);

      // Display PGN and metadata
      $('#move-window').html(data.pgn_data);

      let metadata =
        `<strong>Tournament:</strong> ${data.tournament || "N/A"}<br>
                            <strong>Time Control:</strong> ${data.time_control || "N/A"}<br>
                            <strong>Variant:</strong> ${data.variant || "N/A"}<br>
                            <strong>White:</strong> ${data.white_player || "N/A"} (${data.white_elo || "N/A"})<br>
                            <strong>Black:</strong> ${data.black_player || "N/A"} (${data.black_elo || "N/A"})<br>
                            <strong>Result:</strong> ${data.result || "N/A"}<br>
                            <strong>Termination:</strong> ${data.termination || "N/A"}<br>
                            <strong>Date:</strong> ${data.date || "N/A"}<br>
                            <strong>Starting FEN:</strong> ${startingFen}`;
      $('#annotation-window').html(metadata);

      // Reset move history and controls
      moves = game.history({
        verbose: true
      });
      currentMoveIndex = 0;

      $('#nextBtn').on('click', function() {
        if (currentMoveIndex < moves.length) {
          const move = moves[currentMoveIndex]; // Get the next move
          game.move(move); // Apply the move to the game
          board.position(game.fen()); // Update the board with the new position
          currentMoveIndex++;
        } else {
          console.log("No more moves.");
        }
      });

      $('#prevBtn').on('click', function() {
        if (currentMoveIndex > 0) {
          game.undo(); // Undo the last move
          board.position(game.fen()); // Update the board with the new position
          currentMoveIndex--;
        } else {
          console.log("Already at the first move.");
        }
      });

      $('#startPositionBtn').on('click', function() {
        game.reset(); // Reset the game to its initial state
        game.load(startingFen); // Reload the game with the starting FEN
        board.position(startingFen); // Set the board to the starting FEN
        currentMoveIndex = 0;
      });

      $('#endPositionBtn').on('click', function() {
        while (currentMoveIndex < moves.length) {
          const move = moves[currentMoveIndex];
          game.move(move); // Apply the move
          currentMoveIndex++;
        }
        board.position(game.fen()); // Update the board to the final position
      });
    } else {
      console.error("Failed to fetch PGN:", data.message);
    }
  });
};

I have tried so many different things.

The last thing I tried was to inject the custom fen into the chess.js

var DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';

// Allow injection of a custom FEN for game initialization
window.setCustomFEN = function(fen) {
  DEFAULT_POSITION = fen;
};

and update the load in the index.html

window.loadPGN = function(id) {
  $.getJSON('php/get_pgn.php?id=' + id, function(data) {
    if (data.success) {
      setCustomFEN(data.starting_fen); // ✅ Injecting the custom FEN
      game = new Chess(DEFAULT_POSITION); // ✅ Using the overridden FEN
      board.position(DEFAULT_POSITION);
      game.load_pgn(data.pgn_data);
      moves = game.history({
        verbose: true
      });
      currentMoveIndex = 0;
      $('#move-window').html(data.pgn_data);
    }
  });
};

Background script being fired twice chrome extension manifest v3

The error occurs when I open a page from my background script because I would prefer a full popup page rather than a tiny one.

chrome.action.onClicked.addListener(() => {
  const uri = chrome.runtime.getURL("index.html");

  chrome.tabs.query({}, async (tabs) => {
    const existingTab = tabs.find((tab) => tab.url === uri);

    if (existingTab && existingTab.id) {
      await chrome.tabs.update(existingTab.id, {
        active: true,
      });

      return;
    }

    chrome.tabs.create({ url: uri });
  });
});

Everything is fine until I open that index.html page. Now listeners are being fired twice.

I am using chrome.runtime.create({}) to create a port from my content scripts. I have tried many things but none have solved it.

If it matters I am using webpack to build the extension.

Cypress modyfing window object in test results in cy.window() yielding undefined in next test

I have test suite in cypress.js where in before each test I delete specific database from indexedDB:

beforeEach(() => {
   cy.window().then(win => win.indexedDB.deleteDatabase('test_db'));
});

In each test I use custom command which stubs specific properties on window object:

Cypress.Commands.add('stubDevice', () => {
  Cypress.on('window:before:load', win => {
    // @ts-expect-error TS does not recognize userAgentData global variable
    const userAgentData = { ...win.navigator.userAgentData };
    const mockedUserAgentData = {
      ...userAgentData,
      mobile: true,
    }

    Object.defineProperty(win.navigator, 'userAgentData', {
      value: mockedUserAgentData,
      configurable: true,
    });
  });
});

When test suite is run, first test works fine, however beforeEach callback before second test throws error Cannot read properties of undefined (reading 'indexedDB'). Looks like cy.window() yields undefined and it seems that using defineProperty on win.navigator is a problem, because when I comment out that part of custom command, beforeEach callback works fine before every test. Why that happens and how can I prevent that?

Image gallery filtered layout and zoomed-in hover

So by the title of this post my problem might seem very vague, but I couldn’t come up with a short explanation of my problem.

I’m making a wordpress website for my intern ship and I wanted to add some extra cool things, so I decided to make a cool interactive gallery to showcase projects. I followed a youtube tutorial for the basics, the layout, the drag and zoom functionalities because I have never used javascript before.

I managed to add a cool overlay, automatic zoom and the titles with me and chatgpt, but I never managed to fix two issues. The hover when you are zoomed in and the visual layout of the filtered images.

I know how to fix both issues on paper:
For the filter problem I need to adjust the value of totalRows from 15 to 30 when you filter anything but “All” and change the images per row to 80.

For the hover problem it’s caused by the draglayer laying on top of the images when zoomed in, but lowering the z-index of the drag-layer will make the dragging not work. Also changing the drag functionality to let’s say the gallery creates a really laggy drag cause the gallery and container don’t cover all the images when zoomed in.

I’m really lost and I don’t know what to do anymore so I hope someone here can help me.

i added the full project in a zip file cause it’s to much code to copy paste into this post.

Thank everyone in advance for their help :))

My filter function now:
// Filter functionality
function showAllImages() {
images.forEach(image => {
image.style.display = ‘block’; // Make all images visible
});
}

function filterImages(category) {
    if (category === 'Hybrid space' || category === 'Digital space' || category === 'Physical space') {
        totalRows = 30; 
        imagesPerRow = 80; 
    } else {
        totalRows = 15; 
        imagesPerRow = 40;
    }

    images.forEach(image => {
        const imageCategory = image.getAttribute('data-category');
        if (category === 'all' || imageCategory === category) {
            image.style.display = 'block'; // Show image
        } else {
            image.style.display = 'none'; // Hide image
        }
    });

    // Reapply the grid layout after the filter change
    gsap.to(images, {
        scale: 1,
        opacity: 1,
        delay: 0.5,
        duration: 0.5,
        stagger: {
            amount: 1.5,
            grid: [totalRows, imagesPerRow],
            from: "random",
        },
        ease: "power1.out",
    });
}

// Set active class for buttons
function setActiveButton(activeButton) {
    filterAllBtn.classList.remove('active');
    filterPhysicalBtn.classList.remove('active');
    filterHybridBtn.classList.remove('active');
    filterDigitalBtn.classList.remove('active');
    
    activeButton.classList.add('active');
}

filterAllBtn.addEventListener('click', () => {
    showAllImages(); // Show all images
    setActiveButton(filterAllBtn);
});

filterPhysicalBtn.addEventListener('click', () => {
    filterImages('Physical space'); // Show only physical space images
    setActiveButton(filterPhysicalBtn);
});

filterHybridBtn.addEventListener('click', () => {
    filterImages('Hybrid space'); // Show only hybrid space images
    setActiveButton(filterHybridBtn);
});

filterDigitalBtn.addEventListener('click', () => {
    filterImages('Digital space'); // Show only digital space images
    setActiveButton(filterDigitalBtn);
});

// Initialize with all images shown
showAllImages();

In my console it does changes the values, but it doesn’t show visually in the grid.

For the hover I haven’t started yet.

If anyone is interested in the full code file I can email it to you 🙂

When filtering on one of the last three filters the totalRows chages to 30 and the imagesPerRow changes to 80

“Invalid trigger” error when I ran my bot.js by node

I was just trying to execute my bot script and it throws this error
could anyone help please?

/home/user/Desktop/bot/node_modules/telegraf/lib/composer.js:540
 Error('Invalid trigger');
            ^

Error: Invalid trigger
    at /home/user/Desktop/bot/node_modules/telegraf/lib/composer.js:540:19
    at Array.map (<anonymous>)
    at normaliseTriggers (/home/user/Desktop/bot/node_modules/telegraf/lib/composer.js:538:21)
    at Composer.command (/home/user/Desktop/bot/node_modules/telegraf/lib/composer.js:357:26)
    at Telegraf.command (/home/user/Desktop/bot/node_modules/telegraf/lib/composer.js:48:34)
    at /home/user/Desktop/bot/bot.js:382:9
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/home/user/Desktop/bot/bot.js:381:7)
    at Module._compile (node:internal/modules/cjs/loader:1469:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)

Node.js v20.18.1

I have already tried to reinstall node and telegraf but it doesnt work

My event listener in is not working when using chzn-select class

I tried to create a with the chzn-select class for the province dropdown.
But this class made my addEventListener not work. If I remove it, the addEventListener will work, but I need it to use this class.

My code:

(async () => {
    await loadProvinceList();

    const select = document.createElement('select');
    select.id = 'province';
    select.name = 'province';
    select.className = 'chzn-select';
    select.addEventListener('change', () => {
        console.log('test');
    });

    for (let name in provinceNameCodeMap) {
        const option = document.createElement('option');
        option.value = provinceNameCodeMap[name];
        option.textContent = name;
        select.appendChild(option);
    }

    const provinceParent = document.getElementById('province_parent');
    provinceParent.innerHTML = '';
    provinceParent.appendChild(select);
})();

I tried these but they did not work.

  • select.chosen();
  • $('#province').chosen();
  • jQuery(select).chosen();
  • $('#province').trigger("chosen:updated");
  • $('#province').trigger('liszt:updated');

I’m working on something that someone else did, so I don’t know the details of this class, so I can’t create a repeatable code. I’m sorry about that. I hope you can help me.

How can wrap the data inside restaurant card component?

In my restaurant clone project, restaurant item details are not getting wrapped inside the component.My project also uses Tailwind css, is it possible just to use it to adjust the data inside component?, if it using react how can warp those inside the component?
example image

RestuarantCard.js

import { CDN_URL } from "../utils/constants";

const styleCard = {
    backgroundColor: "#f0f0f0"
 };

const RestuarantCard =(props) =>{
    const {resData} = props;
    const {cloudinaryImageId,name,cuisines,avgRating,costForTwo} = resData?.info;
    return(
       <div className="m-4 p-4 w-[300px] rounded-lg" style={styleCard}>
          <img className = "rounded-lg w-full h-[180px] object-cover" src ={CDN_URL + cloudinaryImageId}/>
          <h3 className="font-bold text-lg truncate">{name}</h3> 
          <h4>{cuisines.join(",")}</h4>
          <h4> {avgRating}</h4>
          <h4> {costForTwo}</h4>
       </div>
    )
 }

 export const withPromotedLabel = (RestuarantCard) => {
   return (props) => {
      return (
         <div>
            <label>Promoted</label>
            <RestuarantCard {...props}/>
         </div>
      )
   }
 }
 export default RestuarantCard;

Body.js


import RestuarantCard, {withPromotedLabel} from "./RestuarantCard";
import { useEffect, useState } from "react";
import Shimmer from "./Shimmer";
import { Link } from "react-router-dom";


const Body = () =>{
   const [listOfRestaurants, setListOfRestraunt] = useState([]); 
   // as soon as we call setListOfRestaurant the  react will call the diff and update the UI
   const [filteredRestuarant, setfilteredRestuarant] = useState([]);
   const [searchText, setsearchText] = useState("");
   
   const RestaurantCardPromoted = withPromotedLabel(RestuarantCard);
   
   
   useEffect(() => {      //react Hook
      fetchData();
    }, []);

    const fetchData = async () =>
    {
      const data = await fetch(
        "https://thingproxy.freeboard.io/fetch/https://www.swiggy.com/dapi/restaurants/list/v5?lat=12.9352403&lng=77.624532&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING" 
      );
      const json = await data.json();
      console.log(json);
      /*const restaurants = json?.data?.cards[1]?.card?.card?.gridElements?.infoWithStyle?.restaurants || [];
      setListOfRestraunt(restaurants); // Keep the full list here 
      setfilteredRestuarant(restaurants); */
      setListOfRestraunt(json?.data?.cards[1]?.card?.card?.gridElements?.infoWithStyle?.restaurants); 
      setfilteredRestuarant(json?.data?.cards[1]?.card?.card?.gridElements?.infoWithStyle?.restaurants); 
     };
   //conditional Rendering
   if(listOfRestaurants.length === 0){
      return <Shimmer />;
   }
   
   
   return(
       <div className="body">
          <div className="filter flex items-center">
          

          <input type="text" className="border border-solid border-black px-3 py-1 ml-5" value ={searchText} onChange={(e) => {setsearchText(e.target.value);}}/>
         
          <button className="search-container  px-4 py-2 bg-green-100 ml-3 rounded-lg" onClick={() => {
               console.log(searchText);
             const filteredRestuarant =  listOfRestaurants.filter((res) => res.info.name.toLowerCase().includes(searchText.toLowerCase()));
         
             setfilteredRestuarant(filteredRestuarant);
            }}>Search</button>
       
          

      
            <div className="search m-3 p-3 items-center">
            <button className="px-5 py-4 bg-grey-500 rounded-lg" 
            onClick={() => {
               const filteredList = listOfRestaurants.filter
               ((res) => res.info.avgRating > 4.3);
               setListOfRestraunt(filteredList);
            }} >Top Rated Restuarant</button>
            </div>
           
            </div>
            <div className="flex flex-wrap">
          { filteredRestuarant.map(restaurant => (
            <Link to = {"/restauarants/" + restaurant.info.id} >{
              restaurant.info.promoted ? (<RestaurantCardPromoted resData={restaurant}/>) : (<RestuarantCard key={restaurant.info.id} resData={restaurant}/>)
            }
               
               </Link> ))//We have looped using map function, also each of item should have unique key(property)
         //The resList is an array of objects, where each object contains a key info, and inside info, there is another key id. Therefore, to access the id field, you need to drill into the info object within each resList item 
          }

 
             </div>  
           
 
             </div>
    )
 }
export default Body; 

RestuarantMenu.js


import useRestaurantMenu from "../utils/useRestaurantMenu";
import Shimmer from "./Shimmer";
import { useParams } from "react-router-dom";



const RestaurantMenu = () => {
    const { resid } = useParams();
    const resInfo = useRestaurantMenu(resid);


    if ( resInfo === null) return <Shimmer />;

 
    const { name, cuisines, costForTwoMessage } = resInfo?.cards[2]?.card?.card?.info;
    const { itemCards } = resInfo?.cards[4]?.groupedCard?.cardGroupMap?.REGULAR?.cards[2]?.card?.card;
    console.log(itemCards);
   return (<div className="Menu">
             <h1>{name}</h1>
             <h2>{cuisines?.join(", ")} - {costForTwoMessage}</h2>
    
            <h2>Menu</h2>
            <ul>   
                {itemCards?.map((item) => (<li  key = {item.card.info.id}>{item?.card?.info?.name} : {item?.card?.info?.price} </li> //map function, dynamically fetch
            ))}
         
            
            </ul>

            
        </div>
    );
};

export default RestaurantMenu;

How can wrap the text inside my restaurant component? please help

how do I use filter on an object

My project wants me to use a function called filterBooks. Tis function’s purpose is to Filter books based on search input. It wants me to use a function from a helper.js called flattenObjectValuesIntoArray. This function loops throught the books object which is in a booklist.js and it flatten object keys into an array so that we search the entire object by the input value.

This is the exact instruction :

The filterBooks() function takes in a search string and a list of books as parameters and returns all of the books that contain an exact match of the search input as an array of objects. Objects in this array should be formatted as books with title, author, and tags properties, similar to the original books array. It should use the flattenObjectValuesIntoArray() function to search all fields within a book object easily.

const filterBooks = (books, barInput) => {
  return books.filter((book) => {
   const values = flattenObjectValuesIntoArray([book]); // Flatten book into values
   return values.some((value) =>
      value.toString().toLowerCase().includes(barInput.toLowerCase())
   );
  });
};

What I expected was when I typed a value from the Books object, the filterBooks function would return the books that had that word or value. but when I searched a word in the search bar nothing happened .

react-three-fiber and react-three/drei orbitcontrols error

I have a very simple scene like so:

import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';

const Scene = () => {
  return (
    <Canvas>
      <OrbitControls />
    </Canvas>
  );
};

export default Scene;

Now when I run this code I get the following runtime error:

Cannot read properties of undefined (reading ‘ReactCurrentOwner’)
TypeError: Cannot read properties of undefined (reading ‘ReactCurrentOwner’)

And if I remove the <OrbitControls /> component it all works fine.
But for my project I do need the orbit controls how do I make this work?

I have experience with regular old three js, but not with the libraries react-three-fiber and the helper library drei. Yet for the project I am working for uses these libraries soo here we are…

Any help would be greatly appreciated.

Communicating between two domains with postMessage()

I was trying to communicate between two tabs opened in the same browser. Both of the tabs have different domain (page1.local and page2.local). I used the following code, but it is working only if the domains are same.

Page1.local

<!DOCTYPE html>
<html lang="eng">
  <head>
    <title>Page 1 - Tab 1</title>
  </head>
  <body>
    <h1>Page 1 - Tab 1</h1>
    <button onclick="sendMessage()">Send Message</button>
    <script>
      const channel = new BroadcastChannel("myChannel");
      channel.addEventListener("message", (event) => {
        console.log("Received message:", event.data);
      });

      function sendMessage() {
        channel.postMessage("Hello from Page 1 - Tab 1!");
      }
    </script>
  </body>
</html>

Page2.local

<!DOCTYPE html>
<html lang="eng">
  <head>
    <title>Page 2 - Tab 2</title>
  </head>
  <body>
    <h1>Page 2 - Tab 2</h1>
    <button onclick="sendMessage()">Send Message</button>
    <script>
      const channel = new BroadcastChannel("myChannel");
      channel.addEventListener("message", (event) => {
        console.log("Received message:", event.data);
      });

      function sendMessage() {
        channel.postMessage("Hi from Page 2 - Tab 2!");
      }
    </script>
  </body>
</html>

I don’t want to use any third-party application for communication. Is there any alternative way to achieve this with JavaScript?

How to use querySelectorAll instead of other methods in targeting multiple elements? [duplicate]

I need to target all the img elements inside .lazy-load-wrapper class and add multiple attribute to it . And I need to use querySelectorAll but I encountered an error Uncaught TypeError: elmnt.setAttribute is not a function. I think I need to loop the element inside querySelectorAll because it is a static Nodelist, but how can I do that?.

Here are the codes:

function theLazyLoader () {
  const eleAttributes = {
    loading: 'lazy',
    class: 'lazy-load-spinner',
  };
  function setMultipleAttributes(elmnt, attributesToSet) {
    Object.keys(eleAttributes).forEach(i => {
      elmnt.setAttribute(i, eleAttributes[i]);
    });
  }
  
  var elements = document.querySelectorAll(".lazy-load-wrapper img");
  for(var i = 0; i < elements.length; ++i){
    setMultipleAttributes(elements[i], eleAttributes); 
  }
}
theLazyLoader();
img {
  width: 400px;
  height: 300px;
  display: block;
  margin: 10px auto;
  border: 0;
}

.lazy-load-spinner {
  background: url("https://cdn.pixabay.com/animation/2023/10/10/13/27/13-27-45-28_512.gif") center center/100px 100px no-repeat #F1F1FA;
}
<div class="lazy-load-wrapper">
  <img src="https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image2.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image3.jpg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image4.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image5.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image6.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image7.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image8.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image9.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image10.jpeg?tr=w-400,h-300" />
</div>