why lose loaded csv data?

iam working google chroom extension using Html And Javascript. my extension have only two Files Popup.html and popup.js…. iam trying to load links by csv one by one when user click search its load next row and alert first name and last name and wait for user to reclick on search button…but there are some issue in this code its working but when i click other windows or tab instead popup.html and then again click on next its not wkork and lost all loaded csv data i want that csv loaded data remain until user click on clear-Data button.
here popup.js

$(document).ready(function() {
  var csvData;
  var currentLine = 1;
  var headers;
  var firstNameIndex;
  var lastNameIndex;
  var streetAddressIndex;
  var cityIndex;
  var stateIndex;
  var tabId;

  // Refactored file upload and parsing into a separate function
  function parseCsvFile(file) {
    Papa.parse(file, {
      complete: function(results) {
        csvData = results.data;
        headers = csvData[0];
        firstNameIndex = headers.indexOf('First Name');
        lastNameIndex = headers.indexOf('Last Name');
        streetAddressIndex = headers.indexOf('streetaddress');
        cityIndex = headers.indexOf('City');
        stateIndex = headers.indexOf('State');
        if (firstNameIndex === -1 || lastNameIndex === -1 || streetAddressIndex === -1 || cityIndex === -1 || stateIndex === -1) {
          alert('Could not find all required columns in the CSV file.');
          $('#csv-file').val(''); // clear the file input field
          return;
        }
        alert('CSV file uploaded and parsed successfully.');
      },
      error: function() {
        alert('Failed to upload or parse the CSV file.');
      }
    });
  }

  // Handler for file input change event
  $('#csv-file').on('change', function() {
    var file = $('#csv-file')[0].files[0];
    if (!file) {
      alert('Please select a CSV file.');
      return;
    }
    parseCsvFile(file);
  });
 
 // Define variables to keep track of the current state
var csvData = null;
var currentLine = 1;
var tabId = null;

// Function to perform a search
function performSearch() {
  if (!csvData) {
    alert('Please upload a CSV file first.');
    return;
  }

  // Get the data row for the current line
  var data = csvData[currentLine];
  var firstName = data[firstNameIndex];
  var lastName = data[lastNameIndex];
  var streetAddress = data[streetAddressIndex];
  var city = data[cityIndex];
  var state = data[stateIndex];

  // Construct the search URL using the street address, city, and state
  var url = 'https://www.truepeoplesearch.com/resultaddress?streetaddress=' + encodeURIComponent(streetAddress) + '&citystatezip=' + encodeURIComponent(city) + ',' + encodeURIComponent(state);

  // Load the search page in the current tab
  if (tabId) {
    chrome.tabs.update(tabId, { url: url });
  } else {
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
      tabId = tabs[0].id;
      chrome.tabs.update(tabId, { url: url });
    });
  }

  // Wait for the page to load
  chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo, tab) {
    if (tabId === tab.id && changeInfo.status === 'complete') {
      // Display the First Name And last name in alert on the active tab
      chrome.tabs.executeScript(tabId, { code: 'alert("First Name: ' + firstName + '\nLast Name: ' + lastName + '");' });

      // Remove the listener so it doesn't run again for other tabs
      chrome.tabs.onUpdated.removeListener(listener);
    }
  });
}

// Function to move to the next line
function moveToNextLine() {
  // Check if csvData exists and there are more lines
  if (csvData && currentLine < csvData.length - 1) {
    // Increment the current line
    currentLine++;

    // Perform the search for the current line
    performSearch();
  }
}

// Attach event listeners to the search and next buttons
$('#search-btn').on('click', function() {
  currentLine = 1;
  performSearch();
});

$('#next-btn').on('click', moveToNextLine);


// Listen for tab changes and save the csvData
chrome.tabs.onActivated.addListener(function(activeInfo) {
  chrome.tabs.get(activeInfo.tabId, function(tab) {
    chrome.storage.local.set({ 'csvData': csvData });
  });
});

// Listen for changes in the storage and update the csvData
chrome.storage.onChanged.addListener(function(changes, namespace) {
  for (var key in changes) {
    if (key === 'csvData') {
      csvData = changes[key].newValue;
    }
  }
});


});

i tried mannytime bbut its lost always

field not getting focus js/html

        <td><input class="reference" type="text" oninput="formatReference(this)" maxlength="7" /></td>
        <td><input class="desc1" type="text" /></td>
        <td><input class="cod" type="text" oninput="acceptOnlyNumbers(this)" /></td>
        <td><input class="qtde_nf" type="text" oninput="acceptOnlyNumbers(this); updateDiferenca(this);" /></td>



function formatReference(input) {
      input.value = input.value.replace(/[^d]/g, "");
      if (input.value.length >= 6) {
        input.value = input.value.slice(0, 5) + "." + input.value.slice(5, 6);
    
        
        var baseNumber = input.value.slice(0, 5);
        var lastDigit = parseInt(input.value.slice(-1), 10);
    
        var sequence = [8, 6, 5, 3, 1, 9, 7, 5, 4, 2, 0];
        var index = (parseInt(baseNumber, 10) - 1) % 11;
        var calculatedLastDigit = sequence[index];
    
        if (calculatedLastDigit === lastDigit) {
          searchDataBase(input);
        } else {
          input.parentElement.parentElement.querySelector('.desc1').value = "";
          input.parentElement.parentElement.querySelector('.cod').value = "";
          alert("cod is " + baseNumber + "." + calculatedLastDigit);
          input.value = "";
        }
      } else {
        input.parentElement.parentElement.querySelector('.desc1').value = "";
        input.parentElement.parentElement.querySelector('.cod').value = "";
      }
    }
    
    
    function searchDataBase(input) {
      var referencia = input.value;
      referencia = String(referencia).replace('.', ''); 
      var searchValue = referencia.slice(0, 5); 
      var found = false;
    
      for (let row of DataBaseData) {
        if (row.codpro === searchValue) {
          found = true;
          input.parentElement.parentElement.querySelector('.desc1').value = row.descpro;
          const codigoMatch = row.descpro.match(/-([a-zA-Z]*d+|/)/);
          if (codigoMatch) {
            input.parentElement.parentElement.querySelector('.cod1').value = codigoMatch[1];
          }
          input.parentElement.parentElement.querySelector('.qtde-nf').focus();
    
          break;
        }
      }
    
      if (!found) {
        input.parentElement.parentElement.querySelector('.desc1').value = "";
        input.parentElement.parentElement.querySelector('.cod').value = "";
        alert("Referência não encontrada");
      }
    }

im trying to get focus on field qtde-nf after i input the right reference. if i put the right reference the fields desc1 and cod are beeing filled automatically. also i wanted after it filled automatically i get focus on qtde-nf field to avoid everyline i stay sending 3 ‘tabs’.

i did several tries calling a function to focus, trying to focus directly after cod and desc1 was filled, tried to set a delay, etc etc. and none worked.

someone can help me please?

how to pass form values and return values of a custom hook when using the useFormik Hook

Hi all im new to reactjs. below is the custom reacthook callled useSubmit that i need to pass and fetch data from. on inspection it acepts a url,data argument and returns the isLoading,response and submit method. I believe i need to make an api call to this useSubmit hook. onsubmit:(values) => {/insert code here/},

import {useState} from "react";

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

/**
 * This is a custom hook that can be used to submit a form and simulate an API call
 * It uses Math.random() to simulate a random success or failure, with 50% chance of each
 */
const useSubmit = () => {
  const [isLoading, setLoading] = useState(false);
  const [response, setResponse] = useState(null);

  const submit = async (url, data) => {
    const random = Math.random();
    setLoading(true);
    try {
      await wait(2000);
      if (random < 0.5) {
        throw new Error("Something went wrong");
      }
      setResponse({
        type: 'success',
        message: `Thanks for your submission ${data.firstName}, we will get back to you shortly!`,
      })
    } catch (error) {
      setResponse({
        type: 'error',
        message: 'Something went wrong, please try again later!',
      })
    } finally {
      setLoading(false);
    }
  };

  return { isLoading, response, submit };
}

export default useSubmit;

I have tried using the hook useSubmit hook directly within the onsubmit(values) => {useSubmit()},
but that violates the rules of hooks as im calling a hook within a hook.I guess i still havent got down some of the react patterns and rules down a pat yet. Hopefully someone can aid me with this

How to send the failure file when user types already exists emailid

Error: Request aborted
at onaborted (C:UsersBivekOneDriveDesktopNewsletter-Signuonode_modulesexpresslibresponse.js:1052:15)
at Immediate._onImmediate (C:UsersBivekOneDriveDesktopNewsletter-Signuonode_modulesexpresslibresponse.js:1094:9)
at process.processImmediate (node:internal/timers:476:21) {
code: ‘ECONNABORTED’

HERE IS THE CODE I HAD WROTE:

const Express = require("express");                 

const body_parser = require("body-parser");

const https = require("https");                    // To send request to external server

const app = Express();

app.use(Express.static("public"));                // To make our static website to dynamic website so that we can load other local path file like css and js

app.use(body_parser.urlencoded({extended:true}));   //if we don't use this then we can't able to fetch data of input

app.get("/",function(req,res){

    res.sendFile(__dirname + "/signup.html");

});

app.post("/",function(req,res){
    const FirstName = req.body.first;    
    const LastName = req.body.last;    
    const Email = req.body.email;
    const data = {                              // We need to create members for those who subscribed our signup
        members:[{                              // here is the syntax
            email_address:Email, 
            status: "subscribed",
            merge_fields:{
                FNAME: FirstName,
                LNAME: LastName,
            }
            
        }]
    } 
    const jsonData = JSON.stringify(data);           // change the javascript data to string data so that mailchimp can recognise it
    const url = "https://us18.api.mailchimp.com/3.0/lists/92a6b8971c";    
    const option = {                                
        method: "POST",
        auth: "Bivek:a40acb902c010418f36154cb92f63edb-us18"
    };
    const request = https.request(url,option,function(response){   // earlier we use https.get for getting data from the external server but here we need to post data to mailchimp server that's why we used https.request
        response.on("data",function(data){
            const errors = JSON.parse(data).errors;
            if(errors){
                res.sendFile(__dirname + "/failure.html",function(err){
                    console.log(err);
                });
            }
            else{
                res.sendFile(__dirname + "/success.html");
            }
        });
        if (response.statusCode === 200) {
            res.sendFile(__dirname + "/success.html");
        }
        else{
            res.sendFile(__dirname + "/failure.html");
        }
        
    }); 
    request.write(jsonData);
    request.end();
})
app.post("/failure",function(req,res){
    res.redirect("/");
})
app.listen("3000",function(){

    console.log("Server is running at port 3000");

});
// Audience ID: 92a6b8971c

after execution of console.log(err) statement it shows the above error
When user inputs the already exists email-id to signup then I want to send failure.html file.

Stretch canvas 100% width but contain in window

I have a canvas that I am stretching with CSS using width: 100%;. It works great to maintain aspect ratio because the height adjusts automatically. But I want it to stop growing when the window is resized so wide that the canvas’ height would be below the fold. Is there an easy CSS property-value for this?

I thought the object-fit property could do that, but I think I’m not understanding something.

Please also note that I have 3 canvases layered on top of each other, so the solution shouldn’t mess with the absolute positioning they have to their ‘position: relative;’ parent container.

How to get subpart of a string in js?

I have this string:

`Traceback (most recent call last):
  File "C:pythonShellFile1818353393.py", line 1, in <module>
    print(hi)
NameError: name 'hi' is not defined`

I want to extract all other parts of this string except for File: “….”

Constraint: in place of print hi there can be any weird type of python expression that can include multiple strings,brackets,spaces etc

Is it possible ?

why is my property from react-awesome-reveal overlapping all the layers in react?

when I remove the “<Fade>” code functions normally, but when I add <Fade> it overlaps all the layers and becomes the top layer in all the situations even though it’s inside a <div> which works fine. I have tried the z-1 and z-10 but it still does not work.

import React from "react";
import { Fade } from "react-awesome-reveal";

export const About = () => {
  return (
    <div name="about" className="w-full h-screen bg-[#124559] text-gray-300">
      <div className="flex px-14 flex-col justify-center items-center w-full h-full">
        <div className="max-w-[1000px] w-full grid grid-cols-2 gap-8">
          <div className="sm:text-right pb-8 pl-4">
            <p className="text-4xl font-bold inline border-b-4 border-pink-600">
              About
            </p>
          </div>
          <div></div>
        </div>
        <div className="max-w-[1000px] w-full grid sm:grid-cols-2 gap-8 px-4">
          <div className="sm:text-right text-4xl font-bold">
            <Fade direction="left">  --> HERE
              <p>Get to know me:</p>
            </Fade>
          </div>
          <div>
            <Fade>
              <p>
                I'm a computer major
              </p>
            </Fade>
          </div>
        </div>
      </div>
    </div>
  );
};
export default About;

different image url each profile (ng-repeat)(ng-src)

result is here

I want a different image url each person profile everytime they’re profile details appeared.
But what happen is it’s only targeted the last url on $scope.imgSrc so they have all same pics which is I don’t like 🙁

I’ve done this and it doesn’t work 🙁

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Details AngularJS</title>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://static.staticsave.com/mycodestyle/style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
</head>
<body>

    <div class="container" ng-app="DetailApp">
        <div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-12 commentBox">
           <div ng-controller="PostController">
                   <h4>Show profile details</h4>       
                <ul>
                  <li ng-repeat='detail in details track by $index'>
                    <div class='detail'>
                      <img class="img-icon" ng-src="{{imageSrc}}" />
                      <div class="com">
                        <span><a href="javascript:void(0);">{{detail.name}}</a></span> {{detail.aboutYou}}
                      </div>
                    </div>
                  </li>
                </ul>              
           </div>
        </div> 
</div>


<script>

var app = angular.module('DetailApp', []);

app.controller('PostController', function($scope, $timeout) {
                
                                // tie the view to ngModule which saves the JSON to localStorage
                $scope.details = localStorage.getItem('details','imageSrc');
                $scope.details = (localStorage.getItem('details','imageSrc')!==null) ? JSON.parse($scope.details) : [];
                localStorage.setItem('details', JSON.stringify($scope.details));


                    var xtimeout = $timeout(function() {
                    $scope.details.unshift({
                        name: "Zandra",
                        aboutYou: "Hi! it's me Zandra and I love Singing <3"
                    });
                    localStorage.setItem("details", JSON.stringify($scope.details));
                }, 1000); 

                    var xtimeout2 = $timeout(function() {
                    $scope.details.unshift({
                        name: "Aaron",
                        aboutYou: "Hi! it's me Aaron from San Antonio Texas"
                    });
                    localStorage.setItem("details", JSON.stringify($scope.details));
                }, 2000); 

                    var xtimeout3 = $timeout(function() {
                    $scope.details.unshift({
                        name: "Jessica",
                        aboutYou: "Hi! it's me Jessica and I really like Pokemon :)"
                    });
                    localStorage.setItem("details", JSON.stringify($scope.details));
                }, 3000); 

                    var logName = $scope.details.some((xdetail)=> xdetail.name === "Zandra");
                    var logName2 = $scope.details.some((xdetail)=> xdetail.name === "Aaron");
                    var logName3 = $scope.details.some((xdetail)=> xdetail.name === "Jessica");

                
                if (logName === true) {
                    $scope.imageSrc='https://i.ibb.co/sbnRv3h/pix1.jpg';
                  $timeout.cancel(xtimeout);                     
                } else {
                    $scope.imageSrc='https://i.ibb.co/sbnRv3h/pix1.jpg';
                }

                if (logName2 === true) {
                    $scope.imageSrc='https://i.ibb.co/v1c2s8f/pix2.jpg';
                  $timeout.cancel(xtimeout2);
                } else {
                    $scope.imageSrc='https://i.ibb.co/v1c2s8f/pix2.jpg';
                }


                if (logName3 === true) {
                    $scope.imageSrc='https://i.ibb.co/xCjYF5Y/pix3.jpg';
                  $timeout.cancel(xtimeout3);
                } else {
                    $scope.imageSrc='https://i.ibb.co/xCjYF5Y/pix3.jpg';
                }
                
});

</script>

</body>
</html>

I don’t know what to do I’m new with angularJS and my script already mess
so help me to solve this problem ASAP I need any clean version also if possible.

Question about difference in Javascript promise error handling based on whether the error is sync or async (node.js)

I am trying to understand promise error handling for the cases of thrown errors and exceptions (code bugs) in the promise executor, comparing them to reject. This is for node.js.

It seems like there are clear differences in the handling of reject vs throw and exceptions.

Some web articles imply there is an implicit try/catch around promises that converts exceptions and throws to rejects, but apparently that is not true, or not always true.

I wrote some test code to study it. That code and the results are below.

Test code:

function delay(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(value => {
            resolve();
        }, ms);
    });
}

function f(delayMs, action) {
    return new Promise((resolve, reject) => {
        if (delayMs == 0) {
            console.log(`f() forcing error type ${action} sync...`);
            if (action == 'exception') {
                console.xxx();
            } else if (action == 'throw') {
                throw new Error('thown error sync');
            } else {
                reject('reject sync');
            }
        } else {
            delay(delayMs).
                then(() => {
                    console.log(`f() forcing error type ${action} after delay...`);
                    if (action == 'exception') {
                        console.yyy();
                    } else if (action == 'throw') {
                        throw new Error('thrown error after delay');
                    } else  {
                        reject('reject after delay');
                    }
                });
        }
    });
}

function main(delayMs, action) {
    f(delayMs, action).
        then(value => {
            console.log('Should not see this');
        }).
        catch(err => {
            if (typeof err == 'object') console.log('In main catch:', err.message);
            else console.log('In main catch:', err);
        }).
        finally(() => {
            console.log('In main finally');
        });
}

main(0, 'exception');
main(0, 'throw');
main(0, 'reject');
main(500, 'reject');
main(1000, 'exception');
main(1500, 'throw');

Output:

f() forcing error type exception sync...
f() forcing error type throw sync...
f() forcing error type reject sync...
In main catch: console.xxx is not a function
In main catch: thown error sync
In main catch: reject sync
In main finally
In main finally
In main finally
f() forcing error type reject after delay...
In main catch: reject after delay
In main finally
f() forcing error type exception after delay...
/mnt/c/Users/test/promise-stackoverflow-2.js:25
                        console.yyy();
                                ^

TypeError: console.yyy is not a function
    at /mnt/c/Users/test/promise-stackoverflow-2.js:25:33

Node.js v18.12.1

For the synchronous case, all three error types are handled the same, being caught in the catch in the main function.

For the asynchronous case, which admittedly involves another Promise, the reject case is still handled in the catch in the main function. But the other two cases (exception and throw) cause a higher level exception and the process exits.

It looks like I can add a catch handler for the delay() promise, and then do a reject in that catch and it will propagate to the main catch handler. I didn’t think I would need to do this – am I missing something?

Also, some articles imply that error handling is easier using async/await. To me, it seemed like if you want to do strict error handling, just using promises was easier.

Adding a Voice Recording Feature in React Native App

I am trying to add a feauture in my React Native App to be able to create a voice note and send send it in my Django Backend(POST API).

I am using import AudioRecorderPlayer from 'react-native-audio-recorder-player'; library.

In my component, I created Buttons using TouchableOpacity. The buttons are “Start Recording”, “Stop Recording”, and “Play Audio”.

When I use any of those buttons to call my methods, I get the following Error:

[00:09:51] null is not an object (evaluating 'RNAudioRecorderPlayer.startPlayer')
at node_modulesreact-native-audio-recorder-playerindex.ts:null in AudioRecorderPlayer#startPlayer
at [email protected]:null in asyncGeneratorStep
at [email protected]:null in _next
at [email protected]:null in Promise$argument_0
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:null in tryCallTwo
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:null in doResolve
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:null in Promise
at [email protected]:null in <anonymous>
at node_modulesreact-native-audio-recorder-playerindex.ts:null in AudioRecorderPlayer

Below is my code:

const startRecording = async () => {
    try {
      const path = await audioRecorderPlayer.startRecorder();
      audioRecorderPlayer.addRecordBackListener((e) => {
      this.setState({
        recordSecs: e.currentPosition,
        recordTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
      })
    })
      setAudioPath(path);
      console.log(path)
  } catch (error) {
    console.error(error);
  }
}

  const stopRecording = async () => {
    try {
      const path = await audioRecorderPlayer.stopRecorder();
      audioRecorderPlayer.removeRecordBackListener((e) => {
        this.setState({
          recordSecs: 0,
        })
      })
      setAudioPath(path);
      console.log(path)
    } catch (error) {
      console.error(error);
    }
  }

  const playRecording = async () => {
    try {
      await audioRecorderPlayer.startPlayer(audioPath);
    } catch (error) {
      console.error(error);
    }
  };
  

Outside of my component is the instance of AudioRecordPlayer();

const audioRecorderPlayer = new AudioRecorderPlayer();

Can framer-motion simultaneously animate a 3D rotation and a layout change?

I’m trying to use Framer Motion v10.6.0 to animate “flipping and dealing a card” at the same time. I’m using a motion.div that changes parents with a fixed layoutId. It should animate changing parents and rotating in 3D (rotateY) at the same time. On their own, these two operations behave as expected, but after a layout change, the 3D rotation is not animated. 2D rotation and translation behave as expected and animate alongside the layout change.

Edit musing-johnson-jyrpf1

I recreated what I am trying here. When executing Change Parents + Rotate 2D + Translate, all animations play correctly – the div spins around 180 degrees and “lands” in its new parent with an offset. Rotate 3D on its own also plays correctly and animates a “flip”. When executing Change Parents + Rotate 3D, I expect to see similar results. Instead, the rotation is applied instantly.

I have also tried using various initial props, such as excluding it and matching the animate prop.

The page bars not hoverring

</body>
    <div id="header">
        <div class="container">
            <nav>
                <img src="logo.png" class="logo">
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Services</a></li>
                    <li><a href="#">Portfolio</a></li>
                    <li><a href="#">Contact</a></li>
                </ul>
            </nav>  
        </div>
    </div>

/css
.container{
    padding: 10px 10%;
}
nav{
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
}
nav ul li{
    display: inline-block;
    list-style: none;
    margin: 10px 20px;
}
nav ul li a{
    color: #fff;
    text-decoration: none;
    font-size: 18px;
    position: relative;
}
nav ul li a::after{
    content: '';
    width: 100%;
    height: 3px;
    background: #ff004f;
    position: absolute;
    left: 0;
    bottom: -6px;
    transition: 0.5s;
}
nav ul li a:hover::after{
    width: 100%;

why isnt the menu bar hovering???????

I was making a haver effect for the pages for my portfolio website everything else worked but the hovering did not,please help

I added ul and used li as i ussually do but it did not work

why does var++ not work but var + 1 works in the following code I wrote? [duplicate]

This function is supposed to output 0 if value passed in is larger than 100 and return (value+1) if the value passed in is lesser than 100.

const counterFunc = (counter) => (counter>100 ? counter = 0: counter+1 );

console.log(counterFunc(55)); //output 56, which is what I want

but when I replace counter+1 with counter++ is returns 55 instead

const counterFunc = (counter) => (counter>100 ? counter = 0: counter++ );

console.log(counterFunc(55)); //outputs 55

I used counter++ initially but when I noticed that I’m not getting the expected result i switched to counter + 1. for some magical (or extremely technical reason) the latter works but the former does not. I would like to know why counter++ doesn’t work in this scenario.

Bookmarklet doesn’t run

I’m new to Javascript, and this bookmarklet I’m trying to make seems to not work. If I remove this one piece of code in the script, everything works.
javascript:(function() {var elems = document.getElementsByTagName('div')for (var i = 0; i<elems.length; i++) { elems[i].style.backgroundColor = 'black';} })();

I tried putting the code into the bookmarklet and using it. Instead of setting all the divs’ background colors to black, nothing happens.