function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RitikRitik 

How to integrate youtube search engine in a visualforce page?

Hi,

I need to Integrate youtube search engine in my visualforce page. So that whenener the user searches the video in search bar, he should get a list of videos present in youtube (same as in youtube website). After that when he clicks one of the video of the list, he should be redirected to that video in youtube.

I have tried an example given in https://developers.google.com/youtube/v3/code_samples/javascript but I'm not able to make it workable.
Any help would be highly appriciated.
Please treat it as urgent.

Thanks in advance! :)

Regards,
R_Shri
Best Answer chosen by Ritik
thsfthsf
Adding another answer for pure Visualforce (no JS).  This is probably more reliable in the long term but the code is quite verbose due to JSON de-serialization.

Part I - Visualforce Page
<apex:page controller="YouTubeSearchController">
    <apex:form>
        <apex:pageBlock title="Search YouTube">
            <apex:inputText value="{!searchText}" />
            <apex:commandButton action="{!search}" value="Search" />
        </apex:pageBlock>
        <apex:pageMessages />
        <apex:pageBlock rendered="{!items != null}">
            <apex:pageBlockTable value="{!items}" var="item" rowClasses="odd,even" styleClass="tableClass">
                <apex:column>
                    <apex:facet name="header">Title</apex:facet>
                    <apex:outputLink value="http://www.youtube.com/watch?v={!item.id.videoId}" target="_blank">{!item.snippet.title}</apex:outputLink>
                </apex:column>
                <apex:column>
                    <apex:facet name="header">Description</apex:facet>
                    <apex:outputText value="{!item.snippet.description}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Part II - Apex Controller
public with sharing class YouTubeSearchController {
    
    public String searchText { get; set; }
    public YouTubeSearchController.Item[] items { get; set; }
    
    private static final String SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search';
    private static final String API_KEY = 'Get a key at - https://console.developers.google.com/';

    public PageReference search() {
        if ((searchText == null) || (searchText == '')) {
            items = null;
            return null;
        }
        
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HttpResponse res = null;
        String endpoint = SEARCH_URL +
            '?part=snippet' +
            '&maxResults=10' +
            '&type=video' +
            '&q=' + EncodingUtil.urlEncode(searchText, 'UTF-8') +
            '&key=' + API_KEY;
        
        req.setEndPoint(endpoint);
        req.setMethod('GET');
        try {
            res = http.send(req);
            System.debug(res.getBody());
        } catch (System.CalloutException e){
            System.debug('ERROR:' + e);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Unable to run search at this time.  Please try again later.'));
            return null;
        }
        
        Response response = (Response)JSON.deserialize(res.getBody(), YouTubeSearchController.Response.class);
        this.items = response.items;
        
        return null;
    }
    
    public class Response {
        public String kind { get; set; }
        public String etag { get; set; }
        public String nextPageToken { get; set; }
        public String prevPageToken { get; set; }
        public YouTubeSearchController.PageInfo pageInfo { get; set; }
        public YouTubeSearchController.Item[] items { get; set; }
    }
    
    public class PageInfo {
        public Integer totalResults { get; set; }
        public Integer resultsPerPage { get; set; }
    }
    
    public class Item {
        public String kind { get; set; }
        public String etag { get; set; }
        public YouTubeSearchController.Id id { get; set; }
        public YouTubeSearchController.Snippet snippet { get; set; }
    }
    
    public class Id {
        public String kind { get; set; }
        public String videoId { get; set; }
    }
    
    public class Snippet {
        public Datetime publishedAt { get; set; }
        public String channelId { get; set; }
        public String title { get; set; }
        public String description { get; set; }
        public YouTubeSearchController.Thumbnails thumbnails { get; set; }
        public String channelTitle { get; set; }
        public String liveBroadcastContent { get; set; }
    }
    
    public class Thumbnails {
        //public YouTubeSearchController.Thumbnail default { get; set; }
        public YouTubeSearchController.Thumbnail medium { get; set; }
        public YouTubeSearchController.Thumbnail high { get; set; }
    }
    
    public class Thumbnail {
        public String url { get; set; }
    }
}

The Visualforce page can of course be modified.  Moving forward, I might use embed an <iframe /> into the page for a quick preview.  But we'll see :)

All Answers

vmanumachu1.393650924860069E12vmanumachu1.393650924860069E12
Try below. Just sampled with Contact and it works. Mark it as best answer if it works, it helps others.

<apex:page standardController="Contact">
<div align = "right">
<form action="http://www.youtube.com/results" method="get" target="_blank">
<input name="search_query" type="text" maxlength="128" />
<select name="search_type">
<option value="">Videos</option>
<option value="search_users">Channels</option>
</select>
<input type="submit" value="Search" />
</form>
</div>
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Information">
<apex:inputField value="{!Contact.FirstName}"/>
<apex:inputField value="{!Contact.LastName}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
RitikRitik
I have one question in this, Can we display search result list in our visualforce page and the on clicking any one of the video from that list we should get redirect to exactly that video in youtube?

I mean to say that like the list we are getting in youtube can we get that on our visualforce page? (without using iframe kind of thing, just a simple list)
thsfthsf
There is probably a better way to do templating, but this is what I could hack out in an afternoon :)
<apex:page>
  <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"/>
  <script>
    jQuery(document).ready(function($) {
      $('#queryform').submit(function(){
        var params = {
          part: 'snippet',
          maxResults: 10,
          q: $('#query').val(),
          key: 'Get a key at - https://console.developers.google.com/'
        };
        var url = 'https://www.googleapis.com/youtube/v3/search?' + $.param(params);
        $.ajax(url,
        {
          success: function(response) {
            var tmpl = $(
              '<div>' +
                '<div>' +
                  '<div style="float:left;">' +
                    '<a target="_blank" class="video"><img class="thumb" style="border-width:0;" /></a>' +
                  '</div>' +
                  '<p style="font-weight:bold;"><a target="_blank" class="title video"></a></p>' +
                  '<p><a target="_blank" class="description video"></a></p>' +
                '</div>' +
                '<div style="clear:both"></div>' +
              '</div>');
            var html = ''
            for (var i = 0; i < response.items.length; i++) {
              var item = response.items[i];
              tmpl.find('.thumb').attr('src', item.snippet.thumbnails.medium.url);
              tmpl.find('.title').text(item.snippet.title);
              tmpl.find('.description').text(item.snippet.description);
              tmpl.find('.video').attr('href', 'http://www.youtube.com/watch?v=' + item.id.videoId);
              html += tmpl.html();
            }
            $('#results').html(html);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + ': ' + errorThrown);
          }
        });
        return false;
      });
    });
  </script>
  <form id="queryform">
    <input id="query" size="256" placeholder="Search YouTube" />
    <input type="submit" id="submit" value="Submit" />
  </form>
  <div id="results"></div>
</apex:page>

I might try to do a controller-based solution using Apex callouts.  The main issue being the lack of client-templating support and questionable upgradability using JavaScript in an Visualforce page.  But if you are in a pinch, this should work.
thsfthsf
Adding another answer for pure Visualforce (no JS).  This is probably more reliable in the long term but the code is quite verbose due to JSON de-serialization.

Part I - Visualforce Page
<apex:page controller="YouTubeSearchController">
    <apex:form>
        <apex:pageBlock title="Search YouTube">
            <apex:inputText value="{!searchText}" />
            <apex:commandButton action="{!search}" value="Search" />
        </apex:pageBlock>
        <apex:pageMessages />
        <apex:pageBlock rendered="{!items != null}">
            <apex:pageBlockTable value="{!items}" var="item" rowClasses="odd,even" styleClass="tableClass">
                <apex:column>
                    <apex:facet name="header">Title</apex:facet>
                    <apex:outputLink value="http://www.youtube.com/watch?v={!item.id.videoId}" target="_blank">{!item.snippet.title}</apex:outputLink>
                </apex:column>
                <apex:column>
                    <apex:facet name="header">Description</apex:facet>
                    <apex:outputText value="{!item.snippet.description}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Part II - Apex Controller
public with sharing class YouTubeSearchController {
    
    public String searchText { get; set; }
    public YouTubeSearchController.Item[] items { get; set; }
    
    private static final String SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search';
    private static final String API_KEY = 'Get a key at - https://console.developers.google.com/';

    public PageReference search() {
        if ((searchText == null) || (searchText == '')) {
            items = null;
            return null;
        }
        
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HttpResponse res = null;
        String endpoint = SEARCH_URL +
            '?part=snippet' +
            '&maxResults=10' +
            '&type=video' +
            '&q=' + EncodingUtil.urlEncode(searchText, 'UTF-8') +
            '&key=' + API_KEY;
        
        req.setEndPoint(endpoint);
        req.setMethod('GET');
        try {
            res = http.send(req);
            System.debug(res.getBody());
        } catch (System.CalloutException e){
            System.debug('ERROR:' + e);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Unable to run search at this time.  Please try again later.'));
            return null;
        }
        
        Response response = (Response)JSON.deserialize(res.getBody(), YouTubeSearchController.Response.class);
        this.items = response.items;
        
        return null;
    }
    
    public class Response {
        public String kind { get; set; }
        public String etag { get; set; }
        public String nextPageToken { get; set; }
        public String prevPageToken { get; set; }
        public YouTubeSearchController.PageInfo pageInfo { get; set; }
        public YouTubeSearchController.Item[] items { get; set; }
    }
    
    public class PageInfo {
        public Integer totalResults { get; set; }
        public Integer resultsPerPage { get; set; }
    }
    
    public class Item {
        public String kind { get; set; }
        public String etag { get; set; }
        public YouTubeSearchController.Id id { get; set; }
        public YouTubeSearchController.Snippet snippet { get; set; }
    }
    
    public class Id {
        public String kind { get; set; }
        public String videoId { get; set; }
    }
    
    public class Snippet {
        public Datetime publishedAt { get; set; }
        public String channelId { get; set; }
        public String title { get; set; }
        public String description { get; set; }
        public YouTubeSearchController.Thumbnails thumbnails { get; set; }
        public String channelTitle { get; set; }
        public String liveBroadcastContent { get; set; }
    }
    
    public class Thumbnails {
        //public YouTubeSearchController.Thumbnail default { get; set; }
        public YouTubeSearchController.Thumbnail medium { get; set; }
        public YouTubeSearchController.Thumbnail high { get; set; }
    }
    
    public class Thumbnail {
        public String url { get; set; }
    }
}

The Visualforce page can of course be modified.  Moving forward, I might use embed an <iframe /> into the page for a quick preview.  But we'll see :)
This was selected as the best answer
RitikRitik
Hey thsf,

This is exactly what I was lloking for.
I have even embedded iframe in it, but the only problem I am facing is I am unbale to make the video fullscreen. I have also added the attribute allowfullscreen="allowfullscreen", but stil I am unable to play the video in fullscreen.

But once again thanks!!!

Thanks and Regards,
Ritik
szad khnszad khn
youtube video download (https://indiakabest.in/youtube-se-video-download-kaise-kare/)  i love to read this blog