Reputation: 1
I’m trying to write a JavaScript script to automate sharing posts on Reddit to unlock the "Sharing Pro" achievement (which requires sharing 100 posts). My script is intended to:
Here’s the code I’ve written so far:
let sharedCount = 0;
function sharePost() {
if (sharedCount >= 100) {
console.log("Achievement unlocked: Shared 100 posts!");
return;
}
// Try to find the share button on the current post
let shareButton = document.querySelector('shreddit-post-share-button');
if (shareButton) {
shareButton.click(); // Open the share popup
setTimeout(() => {
let copyLinkButton = document.querySelector('div[aria-label="Copy link"]');
if (copyLinkButton) {
copyLinkButton.click(); // Click "Copy Link"
sharedCount++;
console.log(`Shared posts: ${sharedCount}`);
} else {
console.log("Copy link button not found!");
}
window.scrollBy(0, 500); // Scroll to the next post
setTimeout(sharePost, 1000); // Repeat after 1 second
}, 1000);
} else {
console.log("Share button not found! Scrolling down...");
window.scrollBy(0, 500); // Scroll down to find more posts
setTimeout(sharePost, 1000); // Repeat after 1 second
}
}
sharePost();
The problem:
The script scrolls the page as expected but is unable to locate the Share button. It ends up scrolling indefinitely without performing any sharing actions.
Here’s the HTML structure of the Share button:
<shreddit-post-share-button appearance="secondary" ...></shreddit-post-share-button>
And the "Copy Link" button inside the popup:
<div tabindex="0" ...>Copy link</div>
What I tried:
I expected document.querySelector('shreddit-post-share-button')
to find the Share button, but it doesn’t. I’ve tried using different selectors, adding delays, and ensuring the page has loaded, but nothing seems to work.
My Questions:
shreddit-post-share-button
element? Could it be related to how Reddit dynamically loads content?Upvotes: 0
Views: 112
Reputation: 362
The reason the script unable to locate the element is it uses lazy loading to dynamically load content as you scroll. This can cause elements like the shreddit-post-share-button
to be unavailable in the DOM initially.
Even if the element exists in the DOM, it might not yet be visible or interactive due to lazy loading or rendering delays.
To fix this, Use a MutationObserver
to watch for changes in the DOM and detect when the shreddit-post-share-button
becomes available.
Upvotes: 0