I'm trying to create a Chrome extension whose sole purpose is to click the like button of a YouTube video. Then, I can map the extension to a shortcut key and press Alt-L
or something to like the video.
I found the XPath of the button using the developer tools.
So, the JavaScript code I have in the extension to click the button is this:
var btn = document.evaluate('//*[@id="watch8-sentiment-actions"]/span/span[1]/button',document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
console.log(btn);
console.log("About to click like");
btn.click();
console.log("Just clicked like");
document.evaluate()
actually finds the button. In the Chrome developer tool's console, I see the output:
<button (all the other button details are printed)...>...</button>
About to click like
Just clicked like
But, it doesn't actually click the button.
However, if i execute the same exact code within the developer tool's console, it will actually click the button.
Anyone know why it would work in the developer tool's console but not from the extension?
Additionally, I downloaded an extension called Custom JavaScript for Websites, which injects JavaScript code into websites. I get the same result (the correct output, but not actually clicking the button) as I do with executing the JavaScript from the extension.
EDIT:
Since I can't post an answer to my own question - for future readers that encounter a similar problem, you simply need to add an event handler to the element, before you can call click()
.
The working code is this:
// Get the element to click
var btn = document.evaluate('//*[@id="watch8-sentiment-actions"]/span/span[1]/button',document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
console.log(btn);
// Attach an event handler to the button
btn.addEventListener('click', function myClick(){
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
});
// Click the button
console.log("About to click like");
btn.click();
console.log("Just clicked like");