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

Ordering tables according to the last column using jQuery

Despite trying various solutions provided in other discussions, I have been unable to get the table to display in descending order based on the Weight Score column. Here is a reference of the table: <table align="center" border="1px" cellpadding="5" id ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Display the content of a Vue file directly on the webpage

I am currently developing a website to showcase UI components using plain CSS. The project is built with Vue, utilizing standard HTML and CSS. One of the key features I am working on is providing users with two views for each component: 'Preview' ...

Tips for controlling HTML elements using JavaScript

I'm currently working on implementing a mouse-over scale effect for an HTML image. I chose to use JavaScript for this task because I need the ability to manipulate multiple elements in different ways simply by hovering over one element. Below is the J ...

My React higher order component implementation is revealing the protected route momentarily

import { useRouter } from "next/router"; import { useEffect } from "react"; import axios from "axios"; export default (ChildComponent) => { const enhanceComponent = (props) => { const router = useRouter(); co ...

Modifying table background color using AJAX and jQuery?

Scenario: My web page is designed to automatically search for a specific cell input by the user. If the cell has been input with a value, the table's background color will turn red; otherwise, it will remain green. Currently, the table has not been p ...

Any tips on how to retrieve my mesh that has disappeared off the screen?

Struggling to find a way to detect when an element goes off screen, can someone provide guidance? My project utilizes WebGL along with Three.js. ...

Effective ways to narrow down data in vuetify v-autocomplete component using Fuse.js

In my application, I am using the Vuetify autocomplete component. This component allows for the use of a custom filter to filter input data. Below is an example of a custom filter for the autocomplete: customFilter (item, queryText, itemText) { const ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...

Rotate the mat-select arrow when the dropdown opens (moving in both upward and downward directions)

Currently, I have a mat-select dropdown icon arrow that toggles facing up or down based on user clicks. However, after selecting an option and closing the dropdown, the arrow remains in the upward position unless further clicked and held. I have attempted ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

A step-by-step guide to adding a checkbox column dynamically within handsontable

I am currently utilizing handsontable within a jsfiddle at http://jsfiddle.net/kc11/cb920ear/1/. My task involves dynamically inserting a checkbox column before the existing data. The structure I am working with appears to be a multidimensional array, as s ...

Elegant transition effects for revealing and hiding content on hover

While customizing my WordPress theme, I discovered a unique feature on Mashable's website where the social buttons hide and show upon mouse hover. I'd love to implement this on my own site - any tips on how to achieve this effect? If you have ex ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Modifying CSS style according to the contents of an HTML element

Creating a room allocation page with multiple panel boxes using Bootstrap. Each box represents a bed - highlighted in red if occupied and green if vacant. Clicking on a green panel redirects to the room allocation page, while clicking on a red panel goes t ...

"Troubleshooting: Why is my AngularJS ng-click not triggering the function

My custom directive fetches a navigation block from a webservice call. I am attempting to click on a navigation link that has an "ng-click" attribute set, which should call the specified function. However, the function is not being executed. Below is my r ...

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...