I have the following code, which is supposed to be a simple example of using the google api javascript client, and simply displays the long-form URL for a hard-coded shortened URL:
<script>
function appendResults(text) {
var results = document.getElementById('results');
results.appendChild(document.createElement('P'));
results.appendChild(document.createTextNode(text));
}
function makeRequest() {
console.log('Inside makeRequest');
var request = gapi.client.urlshortener.url.get({
'shortUrl': 'http://goo.gl/fbsS'
});
request.execute(function(response) {
appendResults(response.longUrl);
});
}
function load() {
gapi.client.setApiKey('API_KEY');
console.log('After attempting to set API key');
gapi.client.load('urlshortener', 'v1', makeRequest);
console.log('After attempting to load urlshortener');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
except with an actual API key instead of the text 'API_KEY'.
The console output is simply:
After attempting to set API key
After attempting to load urlshortener
but I never see 'Inside makeRequest', which is inside the makeRequest function, which is the callback function for the call to gapi.client.load, leading me to believe that the function is not working (or failing to complete).
Can anyone shed some light on why this might be so and how to fix it?
Thanks in advance.
After spending hours googling the problem, I found out the problem was because I was running this file on the local machine and not on a server.
When you run the above code on chrome you get this error in the developer console "Unable to post message to file://. Recipient has origin null."
For some reason the javascript loads only when running on a actual server or something like XAMPP or WAMP.
If there is any expert who can shed some light to why this happens, it would be really great full to learn.
Hope this helps the others noobies like me out there :D
Short answer (http://code.google.com/p/google-api-javascript-client/issues/detail?id=46):
The JS Client does not currently support making requests from a file:// origin.
Long answer (http://en.wikipedia.org/wiki/Same_origin_policy):
The behavior of same-origin checks and related mechanisms is not well-defined
in a number of corner cases, such as for protocols that do not have a clearly
defined host name or port associated with their URLs (file:, data:, etc.).
This historically caused a fair number of security problems, such as the
generally undesirable ability of any locally stored HTML file to access all
other files on the disk, or communicate with any site on the Internet.
Related
I've encountered a paywall and I'm trying to bypass it using javascript in the console. I did some research and found a few different approaches, one of which is changing the requestheader in order to make a given website believe that you got there through a twitter link (thus allowing you to view the content for free). The function I use aims to change the referer by listening to the onBeforeSendHeaders event as specified on https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeSendHeaders. It looks like the following (NOTE: This function is typed and executed directly inside of the devtools console):
function setReferer(x){
x.requestHeaders = x.requestHeaders.filter(function(header){
if(header.name === 'Referer'){
return false
return true
)}
x.requestheaders.push(
{
"name: "Referer",
"value": "https://t.co/" //Twitter website
}
return {requestHeaders: x.requestHeaders};
}
//this example uses chrome browser
chrome.webRequest.onBeforeSendHeaders.addListener(setReferer,
{
urls: ["<all_urls>"],
types: ["main_frame"], },
["requestHeaders", "blocking", "extraHeaders"] //extraHeaders meant to bypass CORS protocol
);
Unfortunately upon refreshing the window, this approach gives me folllowing error:
GET <some_url> net:ERR_BLOCKED_BY_CLIENT
Behind this error is the URL to the source code of the article, which I was able to load and copy into word, so I got the article I was looking for anyway. However I wasn't able to view it inside of the browsers main frame. Note that I am doing this only for the purpose of polishing my coding skills. I am trying to get a better understanding of the more complicated facets of the HTTP protocol, especially the way headers get sent clientside and interpreted serverside. If anyone knows more about the subject or knows / has a resource that he or she wants to share, this would me greatly appreciated!
Trying to use google's translate_tts as my fallback if the browser doesn't support speechSynthesis for my project.
Now I am having some trouble with getting the html5 audio working properly.
Been scratching my head and googling all day on why it wasn't working for me.
Then I came across some articles/forums saying that it's something to do with IIS. So I did a test code outside my site to see what happens, and was surprised this worked properly! But when using the same code in my original project which is running in IIS it doesn't work. AND it works when using IIS EXPRESS. I check the MIME types in IIS and mpeg and mp3 are there.
Even doing it in javascript doesn't work in IIS.
TextToSpeech.Audio = document.createElement("AUDIO");
TextToSpeech.Audio.src = url;
TextToSpeech.Audio.playbackRate = 1;
TextToSpeech.Audio.preload = 'auto';
TextToSpeech.Audio.volume = 1; // 0 to 1;
TextToSpeech.Audio.addEventListener('ended', function () {
//i have some code here...
});
TextToSpeech.Audio.addEventListener('error', function (error) { });
TextToSpeech.Audio.play();
Has anyone encountered this issue and happened to resolve it? Your help will be much appreciated, Thanks!
UPDATE: After some more googling, this might be because I am calling it from within my site hosted in IIS which has a proper hostname and my IIS Express runs the site in localhost:PORT which Google sees as noreferrer?
starting some time in the last few days, google seems to have placed a 'captcha' on this service and made it so that it can no longer be called by a server. so this may all be moot.
it used to be you could ONLY call it as a noreferrer, so i don't think noreferrer is your issue (or may be the least of your issues starting a few days back). one way to workaround the issue in fact was to add ref='noreferrer' to your link.
and this may be your initial issue: using wget, you had to use the -U Mozilla option which makes wget appear to be a browser. if you called the url without that, it didn't return anything. so if there is a way to make your IIS look like a browser when calling the google url, that may work.
this link google text-to-speech artile still does work in a browser, maybe that will help you use it the way you want.
however... starting july 28th, i get a '503 service not available' after using it for years with wget on my linux server. could be because it's metered and i've overrused it... i hope it comes back on. i only use it about 100x/day.
they always said it was 'not public' but it is widely used that way...
so that could be related if you're still trying to call it from IIS which i would think behaves similarly to calling it from a linux server.
I'm working on a simple chrome web store app that uses a new API called chrome.bluetooth. The API is rather new and only available to the google chrome dev channel.
I have managed to discover all devices, search through their services and if they have the service I need to connect, it establishes a connection.
My chrome.bluetooth.onConnection function works fine, it returns a socket which I am attempting to write to:
chrome.bluetooth.onConnection.addListener(function(socket){
log("Connected", arguments);
if (socket) {
sockets.push(socket);
var data = str2ab("hello"); //My string to array buffer converter
chrome.bluetooth.write({ //Try to write to socket
socket:socket,
data:data
},function(){
log("Wrote to socket",socket,data,arguments)
})
}
});
After I attempt to write, chrome.runtime.lastError message is:
"Failed to send data. IOReturn code: 3758097088"
Im not quite sure what I am doing wrong, mainly because I don't understand the error. What does "IOReturn code: 3758097088" mean? I was wondering if anybody knows what I am doing wrong and what this error means?
Cheers,
There have been recent improvements to the API, including a big update to the OS X support; the code would be replaced by chrome.bluetoothSocket.send now. Give that a try.
In the event you have not tracked this down yet, if your running on OSX (at least) that maps to "kIOReturnNoDevice" as defined in IOReturn.h:
http://www.opensource.apple.com/source/xnu/xnu-1504.7.4/iokit/IOKit/IOReturn.h
After tracking the error back through the chrome source code, I determined that this is the error returned by "IOBluetoothRFCOMMChannel writeAsync" in chrome "bluetooth_socket_mac.mm" method "BluetoothSocketMac::Send"
This error is made more obtuse because IOReturn.h refers to 0x2c0 for "kIOReturnNoDevice", but when the constants are defined 0xe0000000 seems to be added to each of them (presumably this is an offset so they don't collide with other constants), thus the decmal value is 3758097088 rather then 704.
I can't tell you exactly what OSX is trying to tell you with that error code, but hopefully that provides you with the context you need to find your issue.
I'm currently working with the SoundCloud API and would like to have a track embed when a button is clicked.
I get two errors:
XMLHttpRequest cannot load http://soundcloud.com/oembed.json?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F48419073. Origin null is not allowed by Access-Control-Allow-Origin.
AND
Uncaught TypeError: Cannot read property 'html' of null
Here is my code:
<button onclick="getPopular()">+1</button>
<div id="track"></div>
<script src="http://connect.soundcloud.com/sdk.js" type="text/JavaScript"></script>
<script type="text/JavaScript">
SC.initialize({
client_id: "**************",
});
var getPopular = function() {
SC.get("/tracks", {limit: 1}, function(tracks) {
var track = tracks[0];
alert("Latest track: " + track.title);
SC.oEmbed(track.uri, document.getElementById("track"));
});
};
</script>
I use an alert in my code to let me know that it is actually taking information from the SoundCloud API. I'm just not sure what else is preventing it from embedding.
Thanks, ahead of time, or looking at my question.
jiggabits
Read a little about Same Origin Policy to understand your main problem better. Ajax, localhost and Chrome/Opera don't go well together. This related question is even better.
Your second problem is due to the Ajax call (somewhere in your API) which doesn't return an html response due to the first error.
Instead of explaining the issue (which is very well explained in the links above), I'll provide a solution. Since you're running on Chrome, there's an workaround for that. Start chrome with this option:
--allow-file-access-from-files
(workaround which I shamelessly borrowed from Pointy)
You could also try running it on Firefox, or hosting it temporarily. :)
P.S. If you plan on doing serious development from your local machine, you may consider installing Apache to serve and test content through http://localhost, thus lifting the file:/// restrictions.
Here are some excellent tools that come with Apache and PHP pre-configured for development:
For Windows: EasyPHP, WAMP.
Cross-platform: XAMPP, BitNami.
If you're getting a track back, the I would try, alert(document.getElementById("track")); to make sure that you're getting your dom element.
What would I need to do to get this example running on my machine?
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available)
I'm looking to access the XML file hosted on w3schools (and not move it to my machine), but run the HTML and Javascript code on my machine. I tried changing the third to last line from:
<button onclick="loadXMLDoc('note.xml')">Get XML</button>
to:
<button onclick="loadXMLDoc('http://www.w3schools.com/ajax/note.xml')">Get XML</button>
thinking this would make it work, but it didn't seem to help. Any suggestions?
Just put the full URL into your browser window which will let your browser get it, then copy/paste and save locally. Javascript won't fetch stuff from outside the domain it's served from (without a fair bit of extra work), due to the Same Origin policy ( a security feature).
You can't go cross domain using AJAX. You should move the XML file to the same server that you have the site files stored on and call it that way.
https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
You need to use the following code in the function that does the AJAX:
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead");
} catch (e) {
alert("error");
}
This only works for Firefox! There are other options which can be passed to enablePrivilege that may be useful.