Search twitter API code-js - javascript

I need to use Twitter's Search API. I read twitter's developer documentation and it says that client side authentication is not recommended anymore. But, since mine is really a small application and on a very tight deadline, I decided to use codebird-js.
Here is my code:
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript" src="codebird.js"></script>
<script type="text/javascript">
function loginTwitter() {
var cb = new Codebird();
cb.setConsumerKey("my_consumer_key","my_consumer_secret");
cb.setToken("my_token", "my_token_secret");
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
alert("hey");
},
true
);
}
</script>
Dont think there is any problem with the callback of search tweets, since this is what is documented in codebird-js.Kindly suggest any alternatives to make the code work.
Also, I enabled the option "Allow application to sign in with twitter" in application settings.

You have to make some syntax corrections to your code and to call the "loginTwitter()" function; the code should be:
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript" src="codebird.js"></script>
<script type="text/javascript">
function loginTwitter() {
var cb = new Codebird();
cb.setConsumerKey("my_consumer_key", "my_consumer_secret");
cb.setToken("my_token", "my_token_secret");
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
alert(JSON.stringify(reply)); //do something with the result
},
true
);
};
loginTwitter();
</script>
And don't forget to download the codebird for javascript and put its files into the same folder as your main file (according to the path that you have put in your script).

Related

Global Constants in background_worker.js and popup.js - Chrome Extention v3

I really want to share constants with all my js files, background_serviceworker.js and popup.js.
const EXTENSION_MODE = {
SEARCH_ONLY: "searchOnly",
FILTER: "filter",
OFF: "off"
}
Just putting vars in the background_serviceworker.js and using getBackgroundPage() seems a bit messy to me (can make the background file very big).
I created constants.js.
// constants.js
var EXTENSION_MODE = Object.freeze({
SEARCH_ONLY: "searchOnly",
FILTER: "filter",
OFF: "off"
})
Inject it to the background-service-worker file (using an answer from here Service worker registration failed. Chrome extension to actually see the errors from the injected script. Without, you only see very general error)
// background.js
try { importScripts("constants.js"); } catch (e) { console.error(e); }
Now popup.js still don't have access to that, because it runs in isolated contexed.
So I Also injected it to the popup.html (In the good old fashion way).
<!-- popup.html -->
<body>
<some-other-elements/>
<script src="./constants.js"></script>
<script src="./popup.js"></script>
</body>
And I can use it in popup.js
// popup.js
console.log("popup: " + EXTENSION_MODE.FILTER);
PS. on content scripts (injected using the chrome.scripting.executeScript), we won't use it. There we need to start using Storage and Messaging https://developer.chrome.com/docs/extensions/reference/storage/
https://developer.chrome.com/docs/extensions/mv3/messaging/

An Alternative to <script> tag if resource don't get loaded

If a script resource could not be found by <script> tag
<script src="link.to.js"> <!-- 404 or 500>
Do I have an alternative to work around it naturally in html?
edit: the source it's in an external server, like
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
There is a way to fallback to another resource if the url fails to load if you are using Service Workers, but that requires https. with service worker you have also the possibility to cache resources and make it available to work offline. (which is a good scenario for things like angular)
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).then(function(response) {
if (response.ok) {
// If we got back a non-error HTTP response, return it to the page.
return response
} else {
// An HTTP error response code (40x, 50x) won't cause the fetch() promise to reject.
fetch('http://example.com/404')
}
})
)
})
Another easier way would be to use something that i have seen used with jQuery a lot where if a cdn fails you can fallback to a local path
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>
No, <script src="link.to.js"> should work if you are linking the relative path correctly.
Make sure the path you provide to the file is correct.

gapi.auth javascript commands are not executed properly

I am trying to follow the sample example from Google's developer tutorial
using updated chrome (version 38.0)
But seems like the gapi.auth functions never reached to the their callbacks
Here is a code example that demonstrate it:
<!doctype html>
<html>
<head>
<title>Google API Client test</title>
</head>
<body>
here will be the use of Oauth 2.0
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
googleApiClientReady = function() {
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: 'XXX',
scope: 'https://www.googleapis.com/auth/youtube',
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
alert('gapi.auth return successfully');
} else {
alert('gapi.auth return with error');
}
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
When I run the above html+JS file- none of the 2 optional alerts of 'HandleAuthResult' are displayed on screen at all - meaning that this function is not called back by 'gapi.auth.authorize'
Did anyone manage to use this library properly?
First of all you need to check if chrome has blocked your popup. It's because popup-opening code is not in on-click handler.
Then you should open chrome's developer console and check "Console" tab for errors.
Also you should specify your domain name and port where your page is located in Google Developer Console like this:
I was able to login into google and receive successful callback
using your code but only after removing "immediate: true" option.
I dont know why but i was getting "immediate_failed" error.

Geo location - JS vs JSON

I am tryign to obtain the geolocation of the user browsing using maxmind's free service
http://j.maxmind.com/app/geoip.js
jQuery.getScript('http://j.maxmind.com/app/geoip.js', function()
{
var country = geoip_city();
console.log("Your location is: " + country);
});
However, outputting javascript code instead of a json seems like a bit of a problem, since it evals the code from a site outside your control. What would be the best practice to handle such scenarios?
This will show user's city.
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script type="text/javascript">
document.write(geoip_city());
</script>

FB.api is not a function

I'm trying to pull all of the posts on a users wall. I got an example running that connects to FB okay, but when I try to use FB.api to get the username (I am definitely successfully connected), I get FB.api is not a function. Some searching found this which suggests that I'm using the wrong API link, but when I try the new one (which seems to connect using the same method) everything firebug NET panel says it loads successfully, there are no errors. . . nothing happens at all.
Here is the code (replace the http://connect.facebook.net/en_US/all.js link with http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php for the code to work up until the error I mentioned):
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
function grab(){
FB.api('/me', function(response) {
alert(response.name);
});
}
function update_user_box() {
var user_box = document.getElementById("user");
user_box.innerHTML =
"<div>"
+ "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
+ " Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>"
+ "</div>"
+ "try me";
FB.XFBML.Host.parseDomTree();
}
</script>
</head>
<body>
<div id='user'><fb:login-button onlogin="update_user_box();"></fb:login-button></div>
<br><br>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init("b07e858317c9069d450023b7500b4511", "xd_receiver.htm", {"ifUserConnected": update_user_box});
</script>
</body>
</html>
thanks for any and all help!
You're using methods from two different SDKs. FB.api is part of the new SDK (all.js), and FB.XFBML.Host.parseDomTree() is part of the old SDK (feature loader). For example, to parse the dom tree with the new SDK, you call FB.XFBML.parse(). I recommend you pick one of the two SDKs, preferably the new SDK if you are just starting since the old SDK is deprecated.
I guess you are not intializing correctly. I had similar issues... it was not clear to me which one is oAuth2.0 and which FB-Connect. It seemed confusing. I followed the example (below), it worked for me. See here
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
Hope this helps.
On a side note, you might need extended permission to access publish_stream, read_stream. You should refer here
Typeoneerror is right, you're mixing SDK's.
Here's how I'm initializing the newer JS SDK, using event.subscribe to be sure the SDK is initialized AND the user has authenticated on the JS side before moving forward with any API calls or letting my game try to load etc.
<div id="fb-root"> </div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 760, height: 1000 }); // use this to increase canvas height
FB.Event.subscribe('auth.login', function(response) {
// You can call your function that requires FB.whatever here...
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
I'm also using the PHP SDK to perform the initial auth... If the user is not authed, I echo a JS redirect to our the login url (available from the PHP SDK method getLoginUrl). Hope that helps.

Categories

Resources