替换YouTube观看<a> with <iframe> embeding the video

时间:2017-01-10 02:26:11

标签: javascript jquery google-chrome-extension

Today is my first day with JavaScript and jQuery.

I have experience with HTML, PHP, Python, CSS.

In my experience, I found the best way to learn was to just do it, learning along the way.

I had an idea for a Chrome extension (no clue if it is original, I just wanted to learn), where on YouTube, you hover over a link to a video and it loads the video in an iframe. Getting it on click is not what I am doing. At the moment I am just using hover. But, I have no idea how to make it an iframe.

manifest.json

{
  "name": "HoverTube",
  "description": "Hover over any video on YouTube and it will begin to play without even having to click it. Perfect for those who are tight on resources, and don't want to load a whole new page for just 1 video.",
  "version": "0.2",
  "manifest_version": 2,

  "content_scripts": [
    {
      "matches": [
        "https://www.youtube.com/*"
      ],
      "js": ["jquery-3.1.1.min.js", "hover.js"]
    }
  ]
}

hover.js

$('body').on('mouseenter', 'a', function(){
    if (this.href.includes("watch")){
            //Take this.href and convert it to <iframe width="560" height="315" src="https://www.youtube.com/embed/linkfromthehref" frameborder="0" allowfullscreen></iframe>
        }

    })

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery的.replaceWith()方法将<a>替换为iframe作为HTML文本,并使用.replace()regular expression修改网址:

$('body').on('mouseenter', 'a', function(){
    if (this.href.includes("watch")){
        $(this).replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/' +this.href.replace(/[^=]*=/,'')+'" frameborder="0" allowfullscreen></iframe>');
    }
})

除了插入它之外,你应该给它一个ID。从UI的角度来看,在页面上选择一个位置来显示iframe并重用该位置可能会更好。可能更好的是,有一个飞出/弹出窗口只在链接悬停时显示iframe,然后在链接不再悬停时销毁它。