How do I get the DOM from a webpage with Chrome Extension Manifest v3?

I’m making a chrome extension to gather data from a webpage. When I try to use document.querySelectorAll() it gets the DOM from the popup, not the current webpage. I tried using chrome’s messaging system to request and send back the HTML but it doesn’t work and gives me errors.

Here’s the important files:

manifest.json

{
  "name": "Name",
  "description": "Description",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["storage", "activeTab", "scripting", "tabs"],
  "host_permissions": [
    "*://*.website.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["*://*.website.com/*"],
      "js": ["content_script.js"]
    }
  ],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "32": "/images/icon.png"
    }
  },
  "icons": {
    "32": "/images/icon.png"
  }
}

popup.js (runs inside popup.html)

function fetchData() {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "fetchData"}, (response) => {
      console.log(response);
    });
  });
}

content_script.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting === "fetchData") {
      sendResponse(document.querySelectorAll(".class"));
    }
  }
);

The error I get from the message sending is “Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.”

When I turn the NodeList to an array, there are no console errors, but it returns a list of “[object Object]”.

Please let me know if there’s a way to do this. I’m just using vanilla js.

Bootstrap Table: how to ignore special characters when using filter control column option

I have a bootstrap table where I’ve set my columns to use data-filter-control="select". When I try to filter a column that contains a special character like < or >. It returns No matching records found. However for other characters like &, = or etc. It works fine without any issues. Is there a way to ignore those special characters when using the filter?

Example code is on https://live.bootstrap-table.com/code/rsquare31/11608

Browser Alert for Right-Click on Image

Does anyone know of a window alert script (browser message) that would make an alert appear when a user right-clicks on an image? The idea is to warn someone that the image is copyrighted, or that they need to cite the source if they want to use it, etc. If such a script exists, is it possible to do this for just a specific image or images on the page, rather than a right-click anywhere on the page? Thanks for any help.

If there is a matching value in the object, how do I rotate the object?

{
 "name": "Albania",
 "topLevelDomain": : [
                      ".al"
                     ],
 "callingCodes": [1 item],
 "capital": "Tirana",
 "altSpellings":  [
                    "AL",
                    "Shqipëri",
                    "Shqipëria",
                    "Shqipnia"
                   ],
 "region": "Europe",
 "population": 2837743,
 "latlng": [2 items],
 "demonym": "Albanian",
 "area": 28748,
 "gini": 33.2,
 "timezones": [1 item],
 "borders": [4 items],
 "nativeName": "Shqipëria",
 "numericCode": "008",
 "flags": {2 items},
 "currencies": [1 item],
 "languages": [
               {
                 "iso639_1": "sq",
                 "iso639_2": "sqi",
                 "name": "Albanian",
                 "nativeName": "Shqip"
                }
               ],
 "translations": {11 items},
},{},{}...

If there is a matching value in the object according to the input from the user, I want to return those objects. For example, I want to find the single object where the id is “Albani” and return that object or I want to find the only value where the id is “Shqip” and return that object.
Api:https://restcountries.com/v2/all

function(input){
 return obj
}

Alert before executing value on select [duplicate]

I have a Select input type with 3 options and want to prompt an Alert window when any option is selected.

This alert has to put the execution of the selected option on hold and give a warning like: “Unsaved changes will be lost. Are you sure you want to continue?”, then I want the option to ‘Cancel’ the execution or to press ‘OK’ and execute.

How can I add a Cancel option inside the alert so it doesn’t execute the selected option and stays on the previously selected option?

See my code below and in the JSFiddle

HTML:

<p> Choose your formation: </p>
<select id="formation" name="formation" onchange="myFunction(formation)">
  <option value="1"> 1-1-2 </option>
  <option value="2"> 1-2-1 </option>
  <option value="3"> 2-1-1 </option>
</select>

<p>
  You chose the following formation: <spam id="demo"> X</spam>.
</p>

Javascript:

function myFunction(formation) {
    alert("Unsaved changes will be lost. Are you sure you want to continue?")

    if(document.getElementById('formation').value == "1") {
    document.getElementById("demo").innerHTML = "1-1-2";
  }
  if(document.getElementById('formation').value == "2") {
    document.getElementById("demo").innerHTML = "1-2-1";
  }
  if(document.getElementById('formation').value == "3") {
    document.getElementById("demo").innerHTML = "2-1-1";
  }
}

React automatically importing all the CSS

So I’m doing a React App, Where the css files remains on src/dist/css, where src is located in the same local of App.js, the thing is I just want to import one single CSS file, but when I’m going to see every css file were automatically imported somehow.

I want to prevent this, because it’s conflicting with the normal css screen.

These are the only things I’m Importing. ( IMAGE )

But All of these are being imported, I don’t know if is something with React or the Server.. ( IMAGE )

How to pass a ion-select value into a pipe in Angular/Ionic?

I am using a ion-select to show currency options. This is my code:

 <ion-item>
        <ion-label>Currency</ion-label>
        <ion-select>
          <ion-select-option value="USD">Dollar</ion-select-option>
          <ion-select-option value="EURO">Euro</ion-select-option>          
        </ion-select>
  </ion-item>

When the user choose one of the currency the prices will shown in that chosen currency. I have read in the Angular documentation there is a currencypipe.

https://angular.io/api/common/CurrencyPipe

I use this pipe like this:

  <ion-col>               
       <ion-badge>Current price: {{item.price | currency}}</ion-badge>
  </ion-col>

You can specify this pipe like this to show the currency the user wants.

<ion-col>               
     <ion-badge>Current price: {{item.price | currency:'USD'}}</ion-badge>
</ion-col>

The requirement I try to achieve is, I want that the user can select te currency from the ion-select and pass this value in the CurrencyPipe. How can I achieve this?

Source I tried:

How can I pass dynamic value to pipe in Angular 8

if else condition inside for loop using angular

I am working on a task where I am looping an array inside a tag & using target=”_blank” attribute but one of the array element should not want this target=”_blank” attribute so what to do?

<ul *ngIf="item.menu">
            <li *ngFor="let subMenu of item.menu">
              <a href="{{subMenu.link}}" target="_blank">{{'landing.menu.' + subMenu.name | translate}}</a>
            </li>
          </ul>

Javascript – Regex match multiple instances [duplicate]

I am new to regex and I am trying to get multiple instances of sections that start and end with a % across a string.
For example, I have the following string:

This happened %Monday% following our forest %trip%. Tomorrow %we will% start packing our things and %return home%.

I am looking to get all the sections that start with % and end with % detected and I cannot seem to get my head around regex… 🙁
I did try a few ways but all it did it selected either everything inside the sentence between first % and last one or just the %.
Thank you.

How to programmatically push a docker image to a docker registry?

I’ve looked online for an answer, but all I could find were articles about dockerizing a node app and pushing it to docker hub or another registry. My question is different.

I programmatically generate some basic files in a folder. One of the root files is a Dockerfile, which I use to build a docker image with child-process. After I build this image, I’d like to push it to my docker registry (not docker hub).

What options am I left with here? Using child-process again after building the image?

Issue with metamask when sending money to the smart contract

I am new to solidity and smart contracts and I am bit confused with sending money from metamask to my smart contract. Everything seems to work fine in remix but when I use metamask I get a revert error message. I am using ganache as my local blockchain

My smart contract looks like this: –

    // SPDX-License-Identifier: GPL-3.0
    pragma solidity ^0.8.10;

   import "@openzeppelin/contracts/access/Ownable.sol";


    contract Bet is Ownable{

     
     uint public Money;  // set variable to display balance on contract
     bool Odd;  // variable to set true or false
     uint TotalDiceNumber = 12;  // dice numbers from 1 - 12
     uint result;  // variable to hold the dice roll
     mapping(address => uint)  allowance;  //allowance for non owners of the contract
     uint  BetValue;  //variable for original bet value
     uint  _amount; //variable to hold value of allowance 
     bool  Active; // is the game active
     
     

     
    constructor() {
    

    }

    

    function isOwner() internal view returns(bool) {
        return owner() == msg.sender;  //returns the address who deployed it
    }
    event BetMade(address player, uint Bet);  //placeholder to send data to front end
     function receiveMoney() public payable  {  // get money(bet) from metamask and put on smart
        emit BetMade(msg.sender, BetValue); // send player and value of bet
        //Money += BetValue;  //added after react
        Money += msg.value;
        BetValue = msg.value;
            if (owner() == msg.sender) {
                Active = false;  // owner doesnt active contract to protect funds
            } else {
                Active = true;  // player activates contract when bet is placed
                require(BetValue <= 20 ether, "Bets must be below 21 Ether"); //player can only 
          bet under 20 ether/ owner can put as much money as they want on
         }
      }
    event BalanceofContract(uint Balcontract);
       function getBalance()public returns(uint) { 
        uint Bal;
        Bal = address(this).balance;
        emit BalanceofContract(Bal);
        return Bal;
        
        
    }
    
    event PlayerSelectOddEven(address player, bool OddEven);
    function selectOddorEven(bool OddEven) public {
        emit PlayerSelectOddEven(msg.sender, OddEven);
        require(msg.sender != owner(), "You are the house and cannot bet");  // house cannot bet
        require(Active = true, "Game not in play. Please place a bet"); // game must be active
        Odd = OddEven;  // create field to enter true for odd or false for Even
        //default is false

    }

    
    function Random() internal view returns(uint) {
        return uint(keccak256(abi.encodePacked
        (block.difficulty, 
        block.timestamp, 
        TotalDiceNumber)));  // create a random number from blockchain.
        //in production would look at chainlink VR but looks like there is a cost so
        //went with a less secure option
    } 
    event RollDiceOutput(address player, uint DiceNumber);
    function Rolldice() public returns(uint){
        emit RollDiceOutput(msg.sender, result);
        uint Outcome;
        require(Active = true, "Game not in play. Please place a bet");  //game must be actvie
        Outcome = Random() % TotalDiceNumber;
        result = Outcome + 1;  // use + 1 to remove 0 out of random sequence
        return result;  // function to create number
        
        }
    function OutcomeDice() public view returns (uint) {
        uint Outcome1;
        Outcome1 = result;
        return Outcome1;
        // function to view number from above function
        }
        
    function numberOddorEven() public view returns (bool) {
        bool OddorEven;  // true for odd false for even
        uint _result;
        _result = result;
            if (_result == 1  ||  _result == 3  || _result == 5 || _result == 7 || _result == 9 || 
          _result == 11) {
                OddorEven = true; 
            } else {
                OddorEven = false;
            }
            return OddorEven;
        
            }
    event Winning(address Player, uint WinningsValue);
    function addAllowance() public   {
        emit Winning(msg.sender, _amount);  
        require(msg.sender != owner(), "You are the house and cannot bet");
        require(Active = true, "Game not in play. Please place a bet");
        address _who = msg.sender; // assign player to variable
        _amount = BetValue * 2; //assign allowance twice as much original bet
        allowance[_who] == _amount;  // set allowance in mapping against player
        
        }

    event Won(address Player, uint Winnings);               
    function WinMoney() public  {  
        emit Won(msg.sender, _amount);
        bool UserInputOdd = numberOddorEven();
        bool decisionOdd = Odd;
        address _who = msg.sender; // assign player to variable
        require(Active = true, "Game not in play. Please place a bet"); 
        require(_amount > 0, "Add the house's money by adding a allowance to collect winning");
            if (UserInputOdd == decisionOdd) {
                address payable to = payable(msg.sender);  //pay the player's address
                to.transfer(_amount); // transfer the winning
                _amount = 0; //zeroed the variable for multiplying the bet
                allowance[_who] = 0; // zeroed the allowance
                BetValue = 0; // zeroed the bet
                Odd = false; // resets the odd/even input
                Active = false;  //disable the game 

            } else {
                _amount = 0;  //zeroed the variable for multiplying the bet
                allowance[_who] = 0;  // zeroed the allowance
                BetValue = 0;  // zeroed the bet
                Odd = false;  // resets the odd/even input
                Active = false;  //disable the game 

                }
            
                                    
         }

        receive() external payable {
        receiveMoney();
      }
   }

On the front end I am trying to add funds to the smart contract: –

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useState } from "react"  //import library for line 9
import { ethers } from "ethers" // import library for ethers
import { abi_file } from "../constants/abi"; // import abi from different file

export default function Home() {
  const [isConnected, setIsConnected] = useState(false);  //to show a button is not connected
  const [signer, setSigner] = useState();

  async function connect() {  //create function to connect metameask
      
    if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed
      try {
        await ethereum.request({ method: "eth_requestAccounts"});
        setIsConnected(true);  // set variable as true
        const connectedProvider = new ethers.providers.Web3Provider(window.ethereum);
        setSigner(connectedProvider.getSigner());
        } catch (e) {
          console.log(e);  // catch and log and errors in console(F12 in chrome)
        }
      } else {
      setIsConnected(false);
      }

}

async function Rolldice() {  //execute function

  if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed

    const contractAddress = "0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7";  // address of the contract
    const abi = abi_file;
    

    const contract = new ethers.Contract(contractAddress, abi, signer);  // calls the contract from the 3 variables
    
   
    try {
     // await contract.Rolldice();  //function will are calling on the sol contract
     const transactionResponse = await contract.Rolldice();
     const transactionReceipt = await transactionResponse.wait();
     var player = (transactionReceipt.events[0].args.player);
     var result = (transactionReceipt.events[0].args.DiceNumber.toString());
      //alert("Dice Number pressed");
      //var x = document.createElement("H3");
      //var t = document.createTextNode("Dice rolled from " + player);
     // x.appendChild(t);
     // document.body.appendChild(x);
      var z = document.createElement("H3");
      var w = document.createTextNode("Dice number is " + result);
      z.appendChild(w);
      document.body.appendChild(z);
           
      
    } catch (error) {
      console.log(error);
    }
  } else {
    document.getElementById("executeButton").innerHTML = 
    "Please install MetaMask";
  }
}

async function receiveMoney() {  //execute function

  if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed

    const contractAddress = "0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7";  // address of the contract
    const abi = abi_file;
    

    const contract = new ethers.Contract(contractAddress, abi, signer);  // calls the contract from the 3 variables
    
   
    try {
     // await contract.Rolldice();  //function will are calling on the sol contract
     const transactionResponse = await contract.receiveMoney();
     const transactionReceipt = await transactionResponse.wait();
      var Balance = (transactionReceipt.events[0].args.Bet.toString());
      //alert("Dice Number pressed");
      //var x = document.createElement("H3");
      //var t = document.createTextNode("Dice rolled from " + player);
     // x.appendChild(t);
     // document.body.appendChild(x);
      var z = document.createElement("H2");
      var w = document.createTextNode("The Balance of the contract is " + Balance);
      z.appendChild(w);
      document.body.appendChild(z);
           
      
    } catch (error) {
      console.log(error);
    }
  } else {
    document.getElementById("executeButton").innerHTML = 
    "Please install MetaMask";
  }
}



  return <div className={styles.container}>


  {isConnected ? 
  <>
  <h2>"Connected!" </h2>

  <p> Please send money to 0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7 but no higher than 20 ethers</p>
  
  <button onClick= {() => receiveMoney()}>Bet Money</button>
  <br></br>
  <br></br>
  <button onClick= {() => Rolldice()}>Roll dice</button>
  <br></br>
  <br></br>
  
  </>
  : (<button onClick={() =>connect()}>Connect</button>) }

   
    </div>;


   }

Can anybody suggest where I am going wrong? Many thanks

Javascript unexpected identifier but works in console

When I create a script as such

    async function a(){
        return 'a';
    }
    console.log(undefined || await a());

The browser (Brave & Edge) gives the error Uncaught SyntaxError: missing ) after argument list

Funnily enough, copy and pasting the exact same code into the debug console runs without a complaint.

Any explanation?

JS remove class Name dynamically

I have a requirement to remove a class name dynamically via js.

The reason to do so is that I’m trying to remove the icon of sorting a specific column from a table.

When I inspect the element – I see I have ng-class with the same class name as the class attribute.

I don’t have any access to the angular file – since it’s a third-party app, but I can write some JS in it.

<th title="" ng-repeat="$column in $columns" ng-class="{
   'sortable': $column.sortable(this),
   'sort-asc': params.sorting()[$column.sortable(this)]=='asc',
   'sort-desc': params.sorting()[$column.sortable(this)]=='desc'
   }" class="col_poi_Id_356 sortable">
</th>

When I’m removing the “sortable” from the class manually from the developer console – It works great.

But when I’m trying to do: element.remove("sortable"); it removes the “sortable” both from the class and from the ng-class and its causes unwanted behavior.

I want to remove a class name only from the class attribute without touching the ng-class.

is that possible?

I don’t have much knowledge in JS, but I tried to find a solution on the google but didn’t find one.

any help, including links, will be much appreciated.

Thanks!