0

我正在学习如何制作网络附加信息,并认为通过制作喜欢YouTube视频的附加信息开始会很有趣。如何让内容脚本点击YouTube视频的LIKE按钮?

我的清单部分与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"); 
    } 

在我的控制台我可以看到日志“点击喜欢按钮”。我也可以看到按钮本身,但“点击”部分永远不会通过,或者至少它不会“喜欢”视频。

如果我检查loged“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&amp;itct=CDQQpUEiEwi0iLq78sLTAhUHz5AKHQxkD1wo-B0" data-tooltip-text="I like this" aria-labelledby="yt-uix-tooltip166-arialabel"> 

如果我把在谷歌浏览器的控制台变量,把它放在一个变量,“点击”它与按钮.click();它的工作原理。但内容脚本没有,我不知道为什么。

+0

你可以交替使用YouTube API:https://developers.google.com/youtube/v3/docs/videos/rate –

回答

0

试试这个代码

var likeButton = document.querySelector('#top-level-buttons > ytd-toggle-button-renderer:nth-child(1) > a > #button') 
if (likeButton) { 
    likeButton.click(); 
}