Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing.

I've tried this method so far:

const photo = document.getElementsByClassName('p137Zd')[0].parentElement

photo.querySelectorAll('div[role="checkbox"]').click()

Unfortunately, an error is being thrown. This snippet of code was designed to trigger a click() event and pick the first photo in an album, but I'm encountering the following error message:

Uncaught TypeError: photo.parentElement.querySelectorAll(...)[0].click is not a function

If anyone has any advice on how to accomplish this task, please share. Thank you!

Answer №1

When using querySelectorAll, you are receiving a group of elements which may result in duplicates from your selection.

A more concise solution would be:

const image = document.querySelector('.img235Fd').parentNode

To ensure accuracy, consider implementing the following code snippet:

image.querySelectorAll('div[role="checkbox"]').forEach(item => item.click());

Answer №2

After trying other solutions in this thread without success, I ended up using as a reference to customize it to fit my needs.

document.querySelectorAll('div[role="checkbox"]:not([aria-label*="Select all"]):not([aria-checked="true&quo  t;])').forEach(div => div.click());

I added the filter

:not([aria-label*="Select all"])
because I suspected that the Select All option was being clicked unintentionally, causing images to be deselected. I also included
:not([aria-checked="true"])
to prevent the unintended unchecking of images.

One thing worth noting is that the images/checkboxes need to be visible on the screen for this script to work properly. This may require scrolling and repeatedly entering the command in the console.

Answer №3

One issue arises when using querySelectorAll as it returns an array-like object without a click() function. While the elements in this array-like object have individual click functions, they cannot be invoked directly from the array-like object (specifically a NodeList).

The solution proposed by @mplungjan involves this method:

photo.querySelectorAll('div[role="checkbox"]').forEach(div => div.click());

which works correctly.

However, you can also define a click function for a NodeList to enable running the initial code :)

NodeList.prototype.click = function() {
    for (let item of this) item.click();
};

document.querySelectorAll(".hd").forEach(item => item.parentNode.querySelectorAll("[type=button]").click());
<div>
    <input type="button" value="1" onclick="console.log(1)">
    <input type="button" value="2" onclick="console.log(2)">
    <input type="button" value="3" onclick="console.log(3)">
    <input type="hidden" class="hd">
</div>
<div>
    <input type="button" value="4" onclick="console.log(4)">
    <input type="button" value="5" onclick="console.log(5)">
    <input type="button" value="6" onclick="console.log(6)">
</div>
<div>
    <input type="button" value="7" onclick="console.log(7)">
    <input type="button" value="8" onclick="console.log(8)">
    <input type="button" value="9" onclick="console.log(9)">
    <input type="hidden" class="hd">
</div>

This illustrates that by defining a click function for a NodeList that triggers all elements within it, we can easily reuse it multiple times.

While @mplungjan's answer is accurate and deserving of acceptance, I opted to provide a new response on introducing the missed feature rather than finding workarounds.

Answer №4

If you zoom out, this script will automatically click on all the checkboxes without a "Select all" label and that are not already checked.

document.querySelectorAll('div[role="checkbox"].QcpS9c.ckGgle:not([aria-label*="Select all"]):not([aria-checked="true"])').forEach(div => div.click());

Answer №5

As I set out to retrieve all my Google photos containing images from 2016 onwards, I encountered a hurdle. The code snippet provided here did offer some assistance, but the repetitive task of pasting it into the console proved to be cumbersome. Hence, I decided to create a loop with a timer for easier copying and pasting into the console. I included explanatory notes to elucidate my reasoning behind each step. (Although there may be room for optimization, this approach gets the job done.)

////////////EFFICIENT WAY TO CHECK ALL PHOTOS IN GOOGLE PHOTOS////////////

let loopCount = 0;
let stopLoop = false;

function loopCheckboxes() { //This function is responsible for identifying non-selected photos
  document.querySelectorAll('div[role="checkbox"].QcpS9c.ckGgle:not([aria-label*="Select all"]):not([aria-checked="true"])').forEach(div => div.click());;
  for (i=0; i<allSelects.length; i++) {
    if (!allSelects[i].checked) {
      allSelects[i].click();
    }
  }
  loopCount++;
  if (loopCount < 500 && !stopLoop) { //Executes the loop 500 times
    setTimeout(loopCheckboxes, 500); //Executes one loop every half a second
  } else {
    console.log("Loop terminated"); //Terminates the loop after a specified number of iterations
  }
}

setTimeout(() => { //Timer function
  stopLoop = true;
  console.log("Timer expired, loop terminated"); //terminates the loops when the timer expires
}, 20000);//20 Second count

loopCheckboxes();

Answer №6

let counter = 0
while (true) {
  let checkboxes = [...document.querySelectorAll('.ckGgle')].filter((item) => item.ariaChecked == 'false')
if (checkboxes.length > 0) {
    counter = 0
  checkboxes.forEach((item) => item.click());
  document.getElementsByClassName("yDSiEe uGCjIb zcLWac eejsDc TWmIyd")[0].scrollBy(0, window.outerHeight);
} else {
    counter++;
    if (counter > 30) break
}
    await new Promise(resolve => setTimeout(resolve, 100));
}

Give this code a shot!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Ajax request not redirecting to correct URL

I have been successfully using ajax requests in my document without any issues. I am looking to retrieve the user's coordinates as they load the document and then pass this data on to other methods for distance calculations. On the loading of the ind ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Cease the firing of ion-change until the values have been successfully loaded from storage

My settings page contains multiple ion-toggle's. There's an onChange method to update local storage when toggled. Standard procedure involves checking existing values in storage on page load and mapping them to the toggles using ngModel. <tab ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

StopDefault and JSON Placement

We have a form that sends data to an external domain using JSONP to avoid cross-domain limitations. Everything is functioning properly except for preventing the default form submission that triggers a page reload. Below is the HTML code for the form: < ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

Perform a Selenium action to click on each individual HTML 'a' tag on

I am attempting to automate clicking on all the "a" tags within a website using Selenium in Python. However, I found that all the "a" tags I want to click have the same structure as shown in the code snippet below. I tried clicking them by their class si ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck. So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Steps to ensure that Vue data is updated to accurately reflect any modifications made by user input in the HTML

I'm currently using Vue to develop a small application that involves copying dynamic HTML content to the user's clipboard once they have completed a form. While everything seems to be functioning correctly, I am encountering an issue where the ch ...

Toggle element visibility upon clicking

<table id="selectsupp"> <tr> <td> <select id="category"> <option value="display" readonly="true">-Shop By Category-</option> <option value="all">All</option> <option val ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

Event handling in Node.js can sometimes result in throwing exceptions

I need advice on how to handle errors or return values from an event in my code. Here is what it looks like: _initConnection(){ try{ const errorValidation = this.errorValidation const HOST = "192.168.2.32" ...