I’m trying to create a userscript that automatically adds a QR code image of the current url to the ‘Share’ menu on a youtube video page.
I know next to nothing of JavaScript, UserScript, HTML, etc.
But, this is what I have so far:
// ==UserScript==
// @name Youtube QR ShareLink
// @description Displays QR of youtube URL
// @version 0.1
// @match http://www.youtube.com/watch*
// @match https://www.youtube.com/?*
// @match http://www.youtube.com/?*
// @match https://www.youtube.com/watch*
// @include http://www.youtube.com/?*
// @include http://www.youtube.com/watch*
// @include https://www.youtube.com/?*
// @include https://www.youtube.com/watch*
// ==/UserScript==
(function () {
var shareDiv = document.getElementById('share-option-container ytg-box');
var qrIMG = 'http://chart.googleapis.com/chart?chl=' + window.location.href + '&chld=M%7C0&cht=qr&chs=125x125';
var img = document.createElement('qrcode');
img.src=qrIMG;
img.width=125;
img.height=125;
shareDiv.appendChild(img);
}());
Unsurprisingly, it doesn’t work.
Could anyone please tell me what it is I’m doing wrong?
Thank you!
You’re using
document.getElementByIdwith a value that isn’t the id of the box – it’s a list of the classes for that element. To use a selector like that, you could do it with a couple of calls todocument.getElementsByClassName, or you could usedocument.querySelector('.share-option-container .ytg-box'), or you could use jQuery to perform that selection.Your second problem is that you’re creating an element called ‘qrcode’, but you should be creating an
imgelement.You’re revised code should look like this:
Note that on YouTube, the element that you’re grabbing doesn’t exist until the share box is actually opened, so you’ll need to actually handle opening the share box first before the rest of your code runs. I’ve tested this in my browser and the above code works well once the share box has been opened, but not before.
You can account for that by using a timer. Change the code to: