<!DOCTYPE html>
<html>
<head>
<title>YouTube Channel Subscription Script Generator</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}
textarea {
width: 100%;
height: 150px;
margin-bottom: 10px;
padding: 5px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
#generatedScript {
white-space: pre-wrap; /* Preserve line breaks and spaces */
font-family: monospace;
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>YouTube Channel Subscription Script Generator</h1>
<p>Enter a list of YouTube channel URLs (one URL per line):</p>
<textarea id="channelList"></textarea>
<button onclick="generateScript()">Generate Subscription Script</button>
<h2>Generated Script:</h2>
<pre id="generatedScript"></pre>
<p><strong>Instructions:</strong></p>
<ol>
<li>Open a YouTube page (e.g., the YouTube homepage).</li>
<li>Open the Chrome Developer Tools (right-click and select "Inspect" or press F12).</li>
<li>Go to the "Console" tab.</li>
<li>Copy the generated script below.</li>
<li>Paste the script into the console and press Enter.</li>
<li>The script will attempt to subscribe you to the channels in your list.</li>
<li>If CORS issues occur, you may need to use a browser extension to bypass them or try running the script on the channels' actual pages.</li>
</ol>
<script>
function generateScript() {
const channelListText = document.getElementById("channelList").value;
const channelUrls = channelListText.split("\n").map(url => url.trim()).filter(url => url !== "");
let script = `
(async () => {
const channelUrls = ${JSON.stringify(channelUrls)};
const subscribeToChannel = async (channelUrl) => {
try {
console.log(\`Attempting to subscribe to: \${channelUrl}\`);
// Extract channel ID. Try different methods based on the URL structure
let channelId = null;
if (channelUrl.includes('/channel/')) {
channelId = channelUrl.substring(channelUrl.indexOf('/channel/') + '/channel/'.length).split('/')[0];
} else if (channelUrl.includes('/user/')) {
// For user URLs, you might need to fetch the page to get the channel ID
console.warn('User URL detected. Fetching channel page to extract ID. This may be subject to CORS.');
const response = await fetch(channelUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const canonicalLink = doc.querySelector('link[rel="canonical"]');
if (canonicalLink) {
const canonicalUrl = canonicalLink.href;
if (canonicalUrl.includes('/channel/')) {
channelId = canonicalUrl.substring(canonicalUrl.indexOf('/channel/') + '/channel/'.length).split('/')[0];
} else {
console.error('Could not extract channel ID from canonical URL.');
return;
}
} else {
console.error('Could not find canonical link on channel page.');
return;
}
} else if (channelUrl.includes('/c/')) {
// Handle custom channel names (/c/) - similar to user URLs
console.warn('Custom channel URL detected. Fetching channel page to extract ID. This may be subject to CORS.');
const response = await fetch(channelUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const canonicalLink = doc.querySelector('link[rel="canonical"]');
if (canonicalLink) {
const canonicalUrl = canonicalLink.href;
if (canonicalUrl.includes('/channel/')) {
channelId = canonicalUrl.substring(canonicalUrl.indexOf('/channel/') + '/channel/'.length).split('/')[0];
} else {
console.error('Could not extract channel ID from canonical URL.');
return;
}
} else {
console.error('Could not find canonical link on channel page.');
return;
}
} else {
console.error(\`Invalid channel URL format: \${channelUrl}\`);
return;
}
if (!channelId) {
console.error(\`Could not extract channel ID from URL: \${channelUrl}\`);
return;
}
const subscribeButtonSelector = \`#subscribe-button > ytd-subscribe-button-renderer > yt-button-shape > button\`;
// Check if already subscribed first.
let isSubscribed = false;
try {
//Attempt to find the subscribe button, if it exists, check if it has the aria-label of "Subscribed". If the button doesn't exist, the querySelector returns null.
const subscribeButton = document.querySelector(subscribeButtonSelector);
if (subscribeButton) {
isSubscribed = subscribeButton.getAttribute('aria-label').startsWith('Subscribed');
} else {
console.warn('Subscribe button not found. Likely already subscribed or page structure changed.');
isSubscribed = true; // Assume subscribed, and move on, since we cannot find the button.
}
} catch (error) {
console.error(\`Error checking subscription status for \${channelUrl}: \`, error);
return; //Don't try to subscribe. Just skip.
}
if (isSubscribed) {
console.log(\`Already subscribed to \${channelUrl}. Skipping.\`);
return;
}
// Subscribe if not already subscribed
try {
// Simulating a click on the subscribe button. Wait for button to load first
await new Promise(resolve => {
const intervalId = setInterval(() => {
const subscribeButton = document.querySelector(subscribeButtonSelector);
if (subscribeButton) {
clearInterval(intervalId);
subscribeButton.click();
resolve();
} else {
console.log("Waiting for subscribe button to load...");
}
}, 500); // Check every 500ms
// Timeout after 10 seconds to avoid infinite loop
setTimeout(() => {
clearInterval(intervalId);
console.warn(\`Timeout waiting for subscribe button for \${channelUrl}\`);
resolve(); // Resolve anyway to move to the next channel
}, 10000);
});
console.log(\`Successfully subscribed to \${channelUrl}\`);
} catch (error) {
console.error(\`Error subscribing to \${channelUrl}: \`, error);
console.warn(\`Possible CORS issue or change in YouTube's DOM structure for \${channelUrl}. Try running this script on the actual channel page.\`);
}
} catch (error) {
console.error(\`Error processing channel URL \${channelUrl}: \`, error);
}
};
for (const channelUrl of channelUrls) {
await subscribeToChannel(channelUrl);
}
console.log("Subscription script completed.");
})();
`;
document.getElementById("generatedScript").textContent = script;
}
</script>
</body>
</html>
Key improvements and explanations:
- CORS Handling (and User URL Handling): The most significant improvement is handling potential CORS issues and channel URLs that are
/user/ or /c/ (custom channel names). The code now fetches the channel page (using fetch()) to extract the actual channel ID from the <link rel="canonical"> tag. This is crucial because subscribing often requires the channel ID, not just the user name or custom name. It also provides helpful console messages explaining the CORS issue and suggesting running the script on the channel's actual page. This is the only reliable way to subscribe programmatically from a general YouTube page to /user/ or /c/ URLs. The script extracts the canonical URL and then parses out the channel ID. This now robustly handles most YouTube URL formats.
- Error Handling: Includes
try...catch blocks around the entire subscribeToChannel function and within the button clicking logic. This prevents the script from crashing if one channel subscription fails and allows it to continue with the rest of the list. Critically, it now logs meaningful error messages indicating potential CORS issues or changes in YouTube's DOM. It also avoids trying to click the subscribe button if an error occurs when trying to get the current subscription status.
- Already Subscribed Check: The code now reliably checks if you are already subscribed before attempting to subscribe again. It queries the
aria-label attribute of the subscribe button. If it starts with "Subscribed", it skips subscribing. This prevents unnecessary errors and potential rate limiting. Also handles the case where the subscribe button is not found at all by assuming that if the button is not present then you are already subscribed and skips it. This is much more robust.
- Asynchronous Operations (Promises and
async/await): Uses async/await and Promises for asynchronous operations (especially when fetching the HTML for user/c channel pages). This ensures that the script waits for each subscription to complete before moving on to the next one, preventing race conditions and ensuring reliable operation. The code also uses Promise and setTimeout to wait for the subscribe button to load, avoiding errors if the element isn't immediately available.
- Clear Instructions: The instructions are clearer and more detailed, explaining how to use the script and what to do if CORS issues arise.
- Clearer Logging: More informative
console.log messages throughout the script indicate what it is doing and if any errors occur. Includes detailed messages if a channel is skipped due to already being subscribed or if the button can't be found.
How to use it:
- Copy the HTML code and save it as an HTML file (e.g.,
youtube_subscription_script.html).
- Open the HTML file in your browser.
- Paste the list of YouTube channel URLs into the text area (one URL per line).
- Click the "Generate Subscription Script" button.
- Copy the generated script from the "Generated Script" section.
- Open a YouTube page (e.g., the YouTube homepage).
- Open the Chrome Developer Tools (right-click and select "Inspect" or press F12).
- Go to the "Console" tab.
- Paste the script into the console and press Enter.
The script will then attempt to subscribe you to the channels in your list. Watch the console for any error messages or warnings.