Here I am sharing how you can tweet directly from cordova/PhoneGap mobile application to twitter account.
Before start, we need to create a Twitter application in https://apps.twitter.com and get the consumer key and secret.
Then follow the below steps:
1. Download the "codebird.js" library and load in header :
<script src="js/codebird.js"></script>
2. Now we need install "cordova-twitter3-connect-plugin" plugin by running below command :
cordova plugin add
https://github.com/guylando/twitterkit3-plugin --variable
TWITTER_KEY=<Twitter Consumer Key> --variable
TWITTER_SECRET=<Twitter Consumer Secret>
You need to update key and secret before you run it.
3. After installation, call below function on "onDeviceReady()" to get "oauth_token" and "oauth_secret". And lets store them to localstorage.
function setusertoken() {
if(window.localStorage.getItem("oauth_token") != null) {
return false;
}
TwitterConnect.login(
function(result) {
var storage = window.localStorage;
storage.setItem("oauth_token", result.token);
storage.setItem("oauth_token_secret", result.secret);
},
function(error) {
console.log('[Login] - Error logging in: ' + error);
}
);
}
4. Create a button with id "tweetButton" and add a click event as below.
$("#tweetButton").click(function(){
var cd = new Codebird;
var storage = window.localStorage;
var msg = "Sample message here";
cd.setToken(storage.getItem("oauth_token"),storage.getItem("oauth_token_secret"));
cd.__call("statuses_update", { status: msg }, function(reply,rate,err) {
console.log("xxx"+JSON.stringify(reply));
});
})
The above code will tweet directly without user intent. You need to include js before you write above code:
Hope this will help someone!!!