YouTube API Academy - youtube

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').

I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

Related

Workbox redirect the clients page when resource is not cached and offline

Usually whenever I read a blog post about PWA's, the tutorial seems to just precache every single asset. But this seems to go against the app shell pattern a bit, which as I understand is: Cache the bare necessities (only the app shell), and runtime cache as you go. (Please correct me if I understood this incorrectly)
Imagine I have this single page application, it's a simple index.html with a web component: <my-app>. That <my-app> component sets up some routes which looks a little bit like this, I'm using Vaadin router and web components, but I imagine the problem would be the same using React with React Router or something similar.
router.setRoutes([
{
path: '/',
component: 'app-main', // statically loaded
},
{
path: '/posts',
component: 'app-posts',
action: () => { import('./app-posts.js');} // dynamically loaded
},
/* many, many, many more routes */
{
path: '/offline', // redirect here when a resource is not cached and failed to get from network
component: 'app-offline', // also statically loaded
}
]);
My app may have many many routes, and may get very large. I don't want to precache all those resources straight away, but only cache the stuff I absolutely need, so in this case: my index.html, my-app.js, app-main.js, and app-offline.js. I want to cache app-posts.js at runtime, when it's requested.
Setting up runtime caching is simple enough, but my problem arises when my user visits one of the potentially many many routes that is not cached yet (because maybe the user hasn't visited that route before, so the js file may not have loaded/cached yet), and the user has no internet connection.
What I want to happen, in that case (when a route is not cached yet and there is no network), is for the user to be redirected to the /offline route, which is handled by my client side router. I could easily do something like: import('./app-posts.js').catch(() => /* redirect user to /offline */), but I'm wondering if there is a way to achieve this from workbox itself.
So in a nutshell:
When a js file hasn't been cached yet, and the user has no network, and so the request for the file fails: let workbox redirect the page to the /offline route.
Option 1 (not always useful):
As far as I can see and according to this answer, you cannot open a new window or change the URL of the browser from within the service worker. However you can open a new window only if the clients.openWindow() function is called from within the notificationclick event.
Option 2 (hardest):
You could use the WindowClient.navigate method within the activate event of the service worker however is a bit trickier as you still need to check if the file requested exists in the cache or not.
Option 3 (easiest & hackiest):
Otherwise, you could respond with a new Request object to the offline page:
const cacheOnly = new workbox.strategies.CacheOnly();
const networkFirst = new workbox.strategies.NetworkFirst();
workbox.routing.registerRoute(
/\/posts.|\/articles/,
async args => {
const offlineRequest = new Request('/offline.html');
try {
const response = await networkFirst.handle(args);
return response || await cacheOnly.handle({request: offlineRequest});
} catch (error) {
return await cacheOnly.handle({request: offlineRequest})
}
}
);
and then rewrite the URL of the browser in your offline.html file:
<head>
<script>
window.history.replaceState({}, 'You are offline', '/offline');
</script>
</head>
The above logic in Option 3 will respond to the requested URL by using the network first. If the network is not available will fallback to the cache and even if the request is not found in the cache, will fetch the offline.html file instead. Once the offline.html file is parsed, the browser URL will be replaced to /offline.

Google Chrome Extension with OAuth

I am trying to integrate OAuth with my chrome extension. I am following the tutorial by google: https://developer.chrome.com/extensions/tut_oauth.html
I create ExOauth from the background.js (defined by me and it is loaded by background.html).
var oauth = ChromeExOAuth.initBackgroundPage({
'request_url': 'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize_url': 'https://www.google.com/accounts/OAuthAuthorizeToken',
'access_url': 'https://www.google.com/accounts/OAuthGetAccessToken',
'consumer_key': 'anonymous',
'consumer_secret': 'anonymous',
'scope': 'https://docs.google.com/feeds/',
'app_name': Test app'
});
oauth.authorize(onAuthorized);
Here is the OnAuthorized method:
onAuthorized = function () {
// Start my application logic.
};
Am I missing something here? When I load the extension, it opens up several "Redirecting...." tabs.
The tutorial seems to be missing one file. If you open chrome_ex_oauth.html, you'll see that it tries to load 3 js files:
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="onload.js"></script>
The onload.js file is not provided. The OAuth contacts example provides such a file, with the following content:
window.onload = function() {
ChromeExOAuth.initCallbackPage();
}
After adding this file, it seems to work just fine.
I know the Question is a bit older but i had the same Problem.
I made the mistake that i want to authenticate two oauth endpoint and call both times the ChromeExOAuth.initBackgroundPage({})
Obviously that's wrong cause i dont want to init my background page twice.
Maybe using the ..._oauthsimple.js will fix that

Consume WCF Rest Service in ASP.net using jquery

I am trying to consume a wcf rest api in a asp.net project using jquery. for doing so i have done:
Created a WCF Rest service source code can be downloaded from here.
Created a ASP.Net project to consume that restAPI using jquery. source code here.
In ASP .Net project on the click of button I am trying to call a REST service. But every time I gets two issues:
calling var jsondata = JSON.stringify(request); in TestHTML5.js throws an error saying "Microsoft JScript runtime error: 'JSON' is undefined"
When I press ignore it continues towards WCF Rest API call but it always returns error (Not Found) function. Rest API never gets called.
Thanks for every one's help in advance.
ANSWER:
Solution and source link can be found on this link.
I have looked at the sample code you provided and the problem is that you are violating the same origin policy restriction. You cannot perform cross domain AJAX calls. In your example the service is hosted on http://localhost:35798 and the web application calling it on http://localhost:23590 which is not possible. You will have to host both the service and the calling application in the same ASP.NET project. You seem to have attempted to enable CORS on the client side using ($.support.cors = true;) but on your service doesn't support CORS.
Another issue saw with your calling page (TestHTML5.htm) is the fact that you have included jquery twice (once the minified and once the standard version) and you have included your script (TestHTML5.js) after jquery. You should fix your script references. And yet another issue is the following line <script type="text/javascript"/> which is invalid.
So start by fixing your markup (I have removed all the CSS noise you had in your markup in order to focus on the important parts):
<!DOCTYPE html>
<html dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>SignUp Form</title>
<script type="text/javascript" src="../Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../Scripts/TestHTML5.js"></script>
</head>
<body>
<button id="Send" onclick="testHTML5OnClick();">
Send Me ID!
</button>
</body>
</html>
and then in your TestHTML5.js you could also clean a little bit. For example your service is listening for the following url pattern json/{id} and accepting only GET verbs and you are attempting to use POST which is not possible. In addition to that you are attempting to use the JSON.stringify method which doesn't make any sense with the GET verb. You should simply send the id as part of the url portion as you defined in your service.
function testHTML5OnClick() {
var id = 5;
var url = "../RestServiceImpl.svc/json/" + id;
var type = 'GET';
callLoginService(url);
}
function callLoginService(url, type) {
$.ajax({
type: type,
url: url,
success: serviceSucceeded,
error: serviceFailed
});
}
function serviceSucceeded(result) {
alert(JSON.stringify(result));
}
function serviceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
Did u add this reference?
script type="text/javascript" src="../../json.js"></script>
I have same problem and search i get this and this result

Embedding NPAPI plugin in background using just Firefox Addon SDK

I have recently developed a NPAPI plugin (using FireBreath) in combination with a Google Chrome Extension. I am embedding the plugin using the background.html page and access it from multiple extension pages. Thus, the plugin remains loaded in the background page (until the extension is unloaded or the browser is closed).
I am now searching for the easiest way to port this extension to Firefox. Using the Addon SDK and it's API, i can reproduce the communication between the addon code and HTML user interface.
As there is no such global background DOM as in the Chrome Extension, how would I load the NPAPI plugin just once, without inserting it in every page of the app UI?
I've seen that using a XUL overlay would allow that - is there a way using just the addon sdk?
Edit: I've created an answer to this question with a minimal solution to this problem using page-workers.
You'll want to look at the page-worker module:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.8/packages/addon-kit/page-worker.html
The caveat I would give is that the NPAPI plugin might have made assumptions about visibility or other details of the environment it is running in that simply don't apply in the page-worker environment. If you run into errors, I'd be interested to hear them!
The following code provides a minimal working solution to the problem using the page-workers as as canuckistani suggested.
Note: This solution requires the addon-sdk's unsafeWindow to access the plugin member methods. If there's a better solution that does not depend on that, feel free to send a me a note/comment.
data/background.html
<html>
<head>
<script type="text/javascript" charset="utf-8">
function pluginLoaded() {
// Create an event once plugin is loaded
// This allows the contentscript to detect plugin state
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("pluginLoaded", true, false, null);
window.dispatchEvent(evt);
}
</script>
</head>
<body>
<object id="myplugin" type="application/x-myplugin" width="0" height="0">
<param name="onload" value="pluginLoaded" />
</object>
</body>
</html>
data/background.js
var module = null;
window.addEventListener("pluginLoaded", function( event ) {
// set the module through unsafeWindow
module = unsafeWindow.document.getElementById("myplugin");
module = XPCNativeWrapper.unwrap(module);
self.port.emit("pluginLoaded");
});
// Handle incoming requests to the plugin
self.port.on("pluginCall", function(msg) {
var response;
if (module) {
// Call NPAPI-plugin member method
response = module[msg.method].apply(this, msg.args);
} else {
response = {error: true, error_msg: "Module not loaded!"};
}
self.port.emit("pluginResponse", {data: response});
});
main.js
// Create background page that loads NPAPI plugin
var plugin = require("page-worker").Page({
contentURL: data.url("background.html"),
contentScriptFile: data.url("background.js"),
contentScriptWhen: "ready"
});
// Send request to plugin
plugin.port.emit("pluginCall", message);

Excel links not loading pages, but when the link is pasted in the browser it works.

I have placed hyperlinks in an excel spreadsheet though my ruby-on-rails application. The links are to some privileged pages that require, After the login I am supposed to taken to the requested page. However, what happens is that after login I lang on the home page of the website. Interestingly, when I right-click the link in the excel and paste the link in the web-browser url, it works as expected. So I don't think it's my app's fault, but rather something in excel that I am missing?
My scenario is pretty much the same as this scenario:
http://www.geekstogo.com/forum/topic/289186-excel-2007-hyperlink-loads-web-login-screen-not-linked-urlplease-help-me/
This issue normally happens in IE and i also faced the same problem.
Solution to this is very simple
Create a redirect.html page in your public folder (public folder because you are using ROR)
Copy this to your redirect.html
<html>
<body>
Please wait, loading your page...
<script type="text/javascript">
function getQuerystring(key) {
key = key.replace(/[\[]/,"\\\[").replace(/ [\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var query = regex.exec(window.location.href);
return query[1];
}
window.location = window.location.protocol + "//" + window.location.host + "/" + getQuerystring('page');
</script>
</body>
</html>
The links you are constructing in excel should be modified
For e.g Old link - http://test.com/post/comments/1
New link should be - http://test.com/redirect.html?page=post/comments/1
You need to pass the part of URL (after base url) as a param
How this works.
When user clicks a link in excel it points to redirect.html and the javascript constructs the actual URL and redirects again to proper page, user will be navigated to actual page if already logged in else redirected to Login/Home page.
Not sure it's really an answer but I had the same problem with my application.
The whole application, including the home page, is protected (I'm using Devise).
So whenever a user wants to access http://myapp, it redirects him to http://myapp/users/sign_in.
I think Devise uses a 301 or a 302 to redirect to the login screens.
My finding is that links clicked in Office and opening in IE cannot accomodate this redirect (no problem when Chrome is the default browser). Does it match your setup?
Ultimately, I have found no other solution but to link directly to the sign-in page... Maybe there are other options but I'm still looking for them.
EDIT: found this article (from 2006) about a bug in Outlook which totally matches our situation.
Again, not a solution, but at least an explanation.
This is a problem with Excel's internal URL handling, which has issues with modern web design patterns (e.g. sessions + redirects).
Here's a client-side solution that bypasses Excel's internal mechanisms and uses the OS default URL handler instead. Note that since it uses macros, this approach requires appropriate security settings.
In your worksheet's VBA module, add the following code:
Option Explicit
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal Operation As String, _
ByVal Filename As String, _
Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
ShellExecute 0, "Open", Target.Address
End Sub
This is based on the answers of two other SO answers.
I have updated the redirect.html in the answer by #Bharath, replacing the regex manipulation with the Web APIs now available:
URL
URLSearchParams
See the original answer by #Bharath for further explanation.
<!DOCTYPE html>
<html lang="en">
<body>
One moment please. We are trying to connect you ...
<script type="text/javascript">
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
const redirectTo = params.get('page');
location = `${url.origin}/${redirectTo}`;
</script>
</body>
</html>
Of course, there is scope to handle errors (e.g. if (params.has('page')) etc.
See also Easy URL Manipulation with URLSearchParams by Eric Bidelman of Google.

Resources