我正在学习如何制作网络扩展程序,并认为开始制作喜欢YouTube视频的扩展程序会很有趣。
我与YouTube互动的明显部分如下:
"content_scripts": [
{
"run_at": "document_end",
"matches": ["*://*.youtube.com/*"],
"js": ["/content_scripts/youtube.js"]
}
],
我的代码如下:
let likeButton = document.querySelector('button[title="I like this"]');
if (likeButton != null) {
likeButton.click();
console.log(likeButton);
console.log("clicked on like button");
}
在我的控制台中,我可以看到日志“点击了按钮”。我也可以看到按钮本身,但“点击”部分永远不会通过,或者至少它实际上并不“喜欢”视频。
如果我检查一下“likeButton”,我可以看到:
<button class="yt-uix-button yt-uix-button-size-default yt-uix-button-opacity yt-uix-button-has-icon no-icon-markup like-button-renderer-like-button like-button-renderer-like-button-unclicked yt-uix-post-anchor yt-uix-tooltip" type="button" onclick=";return false;" title="I like this" aria-label="like this video along with 637 other people" data-post-action="/service_ajax" data-force-position="true" data-orientation="vertical" data-position="bottomright" data-post-data="se=8pH38AERCAASDQoLeHRRQ1FZbEdTem8%3D&itct=CDQQpUEiEwi0iLq78sLTAhUHz5AKHQxkD1wo-B0" data-tooltip-text="I like this" aria-labelledby="yt-uix-tooltip166-arialabel">
如果我把它放在谷歌Chrome控制台的变量中,把它放在一个变量上并用button.click();“点击”它,它就可以了。但内容脚本没有,我不知道为什么。
试试这个代码
var likeButton = document.querySelector('#top-level-buttons > ytd-toggle-button-renderer:nth-child(1) > a > #button')
if (likeButton) {
likeButton.click();
}