Youtube-Js-Api /如何在我的实际网页中包含请求的响应?

时间:2017-07-11 19:05:42

标签: firebase firebase-authentication youtube-data-api youtube-iframe-api

我正在使用Firebase(网络应用)和youtube API开发应用。我们的想法是让用户分享他们的播放列表并进行互动。

1)首先,用户必须表明身份。这部分工作得很好(firebase部分)

2)然后,用户必须接受来自youtube API的一些条件(范围)。

3)Youtube API返回请求的结果。

问题是youtube API会为HTML结构的每个数组项重新创建:HTML> HEAD>身体。此外,响应会跳过我的标题并在空白页面中显示所有内容,而不是像包含PHP一样反应(我知道这是javascript但仍然......)。

我知道解决方案在函数executerequest中休息,但我无法说明如何做到这一点。

请求的代码位于正文的中间,但出于我的帖子的目的,我确实把它分开了。



 var GoogleAuth;
    var SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl';
    function handleClientLoad() {
        // Load the API's client and auth2 modules.
        // Call the initClient function after the modules load.
        gapi.load('client:auth2', initClient);
    }

    function initClient() {
        // Retrieve the discovery document for version 3 of YouTube Data API.
        // In practice, your app can retrieve one or more discovery documents.
        var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';

        // Initialize the gapi.client object, which app uses to make API requests.
        // Get API key and client ID from API Console.
        // 'scope' field specifies space-delimited list of access scopes.
        gapi.client.init({
            'apiKey': '...',
            'discoveryDocs': [discoveryUrl],
            'clientId': '....',
            'scope': SCOPE
        }).then(function () {
            GoogleAuth = gapi.auth2.getAuthInstance();

            // Listen for sign-in state changes.
            GoogleAuth.isSignedIn.listen(updateSigninStatus);

            // Handle initial sign-in state. (Determine if user is already signed in.)
            var user = GoogleAuth.currentUser.get();
            setSigninStatus();

            // Call handleAuthClick function when user clicks on
            //      "Sign In/Authorize" button.
            $('#sign-in-or-out-button').click(function() {
                handleAuthClick();
            });
            $('#revoke-access-button').click(function() {
                revokeAccess();
            });
        });
    }

    function handleAuthClick() {
        if (GoogleAuth.isSignedIn.get()) {
            // User is authorized and has clicked 'Sign out' button.
            $('#sign-in-or-out-button').html('Sign out');
            $('#revoke-access-button').css('display', 'inline-block');
            GoogleAuth.signOut();
        } else {
            // User is not signed in. Start Google auth flow.
            GoogleAuth.signIn();
        }
    }

    function revokeAccess() {
        GoogleAuth.disconnect();
    }

    function setSigninStatus(isSignedIn) {
        var user = GoogleAuth.currentUser.get();
        var isAuthorized = user.hasGrantedScopes(SCOPE);
        if (isAuthorized) {
            $('#sign-in-or-out-button').html('Sign out');
            $('#revoke-access-button').css('display', 'inline-block');
            $('#auth-status').html('Connecté ' +
                ' Granted');

            defineRequest();

            console.log('connecté');

        } else {
            $('#roomRed').html('display', 'block');
            $('#sign-in-or-out-button').html('Sign In/Authorize');
            $('#revoke-access-button').css('display', 'none');
            $('#auth-status').html('Déconnecté' +
                ' Denied');
            console.log('déconnecté');
        }
        // This helper method displays a message on the page.

    }

    function updateSigninStatus(isSignedIn) {
        setSigninStatus();
    }


    function createResource(properties) {
        var resource = {};
        var normalizedProps = properties;
        for (var p in properties) {
            var value = properties[p];
            if (p && p.substr(-2, 2) == '[]') {
                var adjustedName = p.replace('[]', '');
                if (value) {
                    normalizedProps[adjustedName] = value.split(',');
                }
                delete normalizedProps[p];
            }
        }
        for (var p in normalizedProps) {
            // Leave properties that don't have values out of inserted resource.
            if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
                var propArray = p.split('.');
                var ref = resource;
                for (var pa = 0; pa < propArray.length; pa++) {
                    var key = propArray[pa];
                    if (pa == propArray.length - 1) {
                        ref[key] = normalizedProps[p];
                    } else {
                        ref = ref[key] = ref[key] || {};
                    }
                }
            };
        }
        return resource;
    }

    function removeEmptyParams(params) {
        for (var p in params) {
            if (!params[p] || params[p] == 'undefined') {
                delete params[p];
            }
        }
        return params;
    }



    function executeRequest(request) {
        request.execute(function(response) {
            console.log(response);
            for(var i = 0; i< response.items.length; i++){
            console.log(response.items[i].player.embedHtml);
                document.write(response.items[i].player.embedHtml);

            }
        });
    }

    function buildApiRequest(requestMethod, path, params, properties) {
        params = removeEmptyParams(params);
        var request;
        if (properties) {
            var resource = createResource(properties);
            request = gapi.client.request({
                'body': resource,
                'method': requestMethod,
                'path': path,
                'params': params
            });
        } else {
            request = gapi.client.request({
                'method': requestMethod,
                'path': path,
                'params': params
            });
        }

        executeRequest(request);
    }

    /***** END BOILERPLATE CODE *****/


    function defineRequest() {
        // See full sample for buildApiRequest() code, which is not
// specific to a particular youtube or youtube method.




        buildApiRequest('GET',
            '/youtube/v3/playlists',
            {
                'mine': 'true',
                'maxResults': '25',
                'part': 'snippet,contentDetails,player',
                'onBehalfOfContentOwner': '',
                'onBehalfOfContentOwnerChannel': ''


            });

/*
        buildApiRequest('GET',
            '/youtube/v3/playlistItems',
            {
                'playlistId': "PLsvlo6Soc2pc2ZlereiehdPRhm0eKjSxI",
                'maxResults': '25',
                'part': 'snippet,contentDetails'
            });
*/
    }
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mes vidéo </title>
<style>

</style>
</head>
<body>
 
<button id="sign-in-or-out-button"
        style="margin-left: 25px">Sign In/Authorize</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">Revoke access</button>

<div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>


<div id="video-container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
        onload="this.onload=function(){};handleClientLoad()"
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

</body>

</html>
&#13;
&#13;
&#13;

先谢谢你

0 个答案:

没有答案