I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.
The first script shows the API running
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url(login, api_key, func, value) {
var value = document.getElementById('input-refcode').value;
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
func(response.data.url);
}
);
}
Second is a script that shares a text via Twitter using on-click
$('#twitter').on('click', function() {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
win.focus();
});
Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example
$('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
win.focus();
});
I tried this solution but the browser flagged the function as a pop-up
$('#twitter').on('click', function() {
var base_url = window.location.origin,
hash_bang_twitter = "/%23/sign-up?referral=",
referral_code = document.getElementById('input-refcode').value;
get_short_url(login, api_key, function(short_url) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
win.focus();
});
});
There is no need to, you can simply wrap
$('#twitter').on('click', function() {
get_short_url(login, api_key, function(short_url) {
win = ...
win.focus();
});
});
I'm no pro at js, but this seems fairly simple. I have not tested this.
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url() {
var value = ('#input-refcode').val();
var result = '';
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
result = response.data.url;
}
);
return result;
};
$('#twitter').on('click', function() {
var short_url = get_short_url(function(short_url)
if (short_url !== '') {
win = window.open('https://twitter.com/intent/tweet?text=' + encodeURI("Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us! " + short_url));
win.focus();
}
});
Related
This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6
I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>
Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.
Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();
I'm trying to log in into gmail account using javascript, and I have a problem:
after I insert my email and press 'next', the page redirect me to new url asking for my password. my question is, How can I monitor the current url and know when it changes? Im trying to use page.onUrlChanged but it doesn't work
test.open(url, function(status) {
test.page.evaluate(function (email, password) {
document.getElementById('Email').value = email;
document.getElementById('next').click();
test.page.onUrlChanged = function(targetUrl) {
console.log(targetUrl);
}
}, email, password);});
you can use phatomjs for log URL change..below is simple code for that
var webPage = require('webpage');
var page = webPage.create();
page.onUrlChanged = function(targetUrl) {
console.log('New URL: ' + targetUrl);
};
find more about phantomjs
http://phantomjs.org/api/webpage/handler/on-url-changed.html
or
You can use
window.onblur = function() { console.log('blur'); }
I need to login throw google in my page. I got my clientID and set the redirect_uri path in Google Console but when I am trying to login it is giving me the following error. I am integrating this on my asp.net page.
Error:
400. That’s an error.
Error: redirect_uri_mismatch
Application: odiyaDoctor
You can email the developer of this application at: odiyadoctor#gmail.com
The redirect URI in the request: http://localhost/immediateHelp.aspx did not match a registered redirect URI.
My requirement is when user will login by google on first page(UserLogin.aspx) and after successful login the next page(i.e.immediateHelp.aspx) will come. I am explaining my all code and google credentials below.
UserLogin.aspx:
</i>
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '*************************g96b1elfa8.apps.googleusercontent.com';
var REDIRECT = 'http://localhost/immediateHelp.aspx';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function googleLogin() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
console.log('its error', e);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
getUserInfo();
loggedIn = true;
window.location.href = "immediateHelp.aspx";
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
console.log('user info',user);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
</script>
In the above page the bellow error is coming in catch section.
at http://localhost:3440/UserLogin.aspx:92:32
UserLogin.aspx:103 its error DOMException: Blocked a frame with origin "http://localhost:3440" from accessing a cross-origin frame.
at Error (native)
clientID set in google.
Client ID for web application
Client ID
***************************************1ctsjaeg96b1elfa8.apps.googleusercontent.com
Client secret
*********oGbT13hv3S
Redirect URIs
https://localhost/immediateHelp.aspx
JavaScript origins
https://localhost
Here i need when user will logged in successfully,it will redirect to the immediateHelp.aspx page and in this page user can do the logout.Please help me to resolve these errors.
`"http://localhost/immediateHelp.aspx" != "https://localhost/immediateHelp.aspx"
The URL must be character perfect
So i have this code, with should connect to google api and get some info of the user. The problem however is that the link which starts the login function doesn't work.
This is a java RESTful project so its built via maven and deployed on a tomcat server if that helps.
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascipt'>
$(document).ready(function(){
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'sercret';
var REDIRECT = 'myredirect';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var url1 = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login(){
var win = window.open(url1, 'windowname1', 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
});
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: 'jsonp'
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: 'jsonp'
});
}
/*credits: http://www.netlobo.com/url_query_string_javascript.html*/
function gup(url, name) {
name = name.replace(/[\\\\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regexS = '[\\#&]'+name+'=([^&#]*)';
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results === null )
return ;
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
});
</script>
</head>
<body>
<a href="#" onclick='login()' id='loginText'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id='myIFrame' style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>
A Small Error, big waste of time :)
<script type='text/javascript'>
You have missed the 'r' in javascipt
This is looking for a function called login:
onclick='login()'
However, no such function exists in the current scope. It was defined only within the scope of the document.ready handler:
$(document).ready(function () {
function login() {
//...
}
});
So it's not visible outside of the handler. In order to make it visible, define it outside:
function login() {
//...
}
$(document).ready(function () {
//...
});
You generally don't need to define your functions in document.ready, it's mainly for waiting until the DOM is loaded before evaluating selectors. You can define functions within it, if those functions don't need to exist outside its scope.
Another alternative would be to bind it within the scope that it's defined, rather than in-line in the markup. Something like this:
$(document.ready(function () {
function login() {
//...
}
$('#loginText').click(login);
});