How to unattach gapi- auth2.attachClickHandler on a condtion - javascript

I am using the google auth for client (gapi) in my code and I have this onLoad event:
<script>
function onLoad() {
gapi.load('auth2', function () {
auth2 = gapi.auth2.init();
var additionalParams = {};
auth2.attachClickHandler('signinButton', additionalParams, onSignIn, onSignInFailure);
//auth2.attachClickHandler('btnGoRegister', additionalParams, onRegisterIn, onSignInFailure);
});
}
</script>
As you can see above, I am attaching a click handler for my Signin button which works fine. The other part is that for the Register button, I have to enable/disable the button and associated events on a condition which works fine for other auth (like FB).
The problem here is that once the attachClickHandler is invoked, then I am unable to in unattach it so that if my condition is not true, then the Google popup screen should not be invoked (currently if it is invoked once then it will always be shown irrespective of my condition).
Does anyone have any idea on how to achieve this?
Thanks

It looks like Google Sign-In API does not support a method for un-attaching the click handler. On the other hand they have a disconnect() & signOut() function, but I don't think it achieves what you want.
One solution is to add an additional button which handles the decision of loading the Google Auth API and preforms the click on signinButton. The signinButton can be hidden using css.
I don't have the api up & running but the code should look something like:
const GoogleSignInButton = 'signinButton';
const GoogleDecisionGateSignInButton = 'googleDecisionGateButton';
function onLoad() {
document.getElementById(GoogleDecisionGateSignInButton).addEventListener("click", GoogleDecisionGateButton);
}
function GoogleDecisionGateButton() {
if (ShouldUseGoogleSigninButton()) {
LoadGoogleAuthApi();
ClickGoogleAuthButton();
}
}
function ShouldUseGoogleSigninButton() {
return true; // Replace this with logic to decided if user should use Google API Auth button or not.
}
function LoadGoogleAuthApi() {
gapi.load('auth2', function () {
auth2 = gapi.auth2.init();
var additionalParams = {};
auth2.attachClickHandler(GoogleSignInButton, additionalParams, onSignIn, onSignInFailure);
//auth2.attachClickHandler('btnGoRegister', additionalParams, onRegisterIn, onSignInFailure);
});
}
function ClickGoogleAuthButton() {
document.getElementById(GoogleSignInButton).click()
}
HTML:
<button id="signinButton" type="button"></button>
<button id="googleDecisionGateButton" type="button"></button>
CSS:
#signinButton { display: none !important }

Related

How to bind window close event in vuejs

I need to bind leave page and close/reload window event to prevent data lost.
I resolved the reload window issue but can't 2 others.
Some of my codes are following:
<script>
window.onbeforeunload = popup; // bind reload page event
function popup() {
return '';
}
export default {
beforeRouteLeave(to, from, next) { // bind leave page event
var result = confirm("Are you sure to leave page? Changes may not be saved.");
if(result) {
next();
}
}
}
</script>

GoogleAuth.signOut() does not work

I have a google sign-in button on my page, using gapi.signin2.render to render the button (https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid-options).
However it ALWAYS renders as signed-in, despite calling GoogleAuth.signOut(). In fact I can actually call GoogleAuth.signOut() and immediatly check GoogleAuth.isSignedIn.get() to check the state and returns as true.
Does anyone know how to fix this? My sign-out code is as follows:
var GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.signOut().then(() => {
var status = GoogleAuth.isSignedIn.get(); //ALWAYS TRUE!!!!
alert('IP.common.oAuth.signOut: signin status: ' + status);
});
This should be work fine. Delete then(this.props.onLogoutSuccess)) if you don't need it.
signOut() {
if (window.gapi) {
const auth2 = window.gapi.auth2.getAuthInstance()
if (auth2 != null) {
auth2.signOut().then(auth2.disconnect().then(this.props.onLogoutSuccess))
}
}
}
Very nice lib, if you wanna learn how to work with Google API https://github.com/anthonyjgrove/react-google-login. Yes it's react, but methods should be similar, I think.

Reload the page using sammy.js

I am using sammy.js for single page application in asp.net mvc. Everything is fine, but I am facing one problem which is that I can not reload the page. For example When I am in the dashboard my URL is
http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard
layout.cshtml
<script>
$(function () {
var routing = new Routing('#Url.Content("~/")', '#page', 'welcome');
routing.init();
});
</script>
routing.js
var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = defaultRoute;
return url;
}
return {
init: function () {
Sammy(contentSelector, function () {
this.get(/\#\/(.*)/, function (context) {
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run('#/');
}
};
}
I want to reload the page by clicking the dashboard menu/link. But click event not firing because link is not changing. But if I want to go another page then it is fine. Please help me out. Thanks.
I think you have to append the same partial again. You can't "update" the partial in that meaning.
As you say in your post, when you click another link and then back again it works.
That's what you'll have to do. Append the same page/partial again, by doing that you clear all variables and recreate them, by that simulating a refresh.
EDIT: Added example
Observe that I didn't copy your code straight off but I think you'll understand :)
And I don't use hash (#) in my example.
var app = Sammy(function () {
this.get('/', function (context) {
// context is equalient to data.app in the custom bind example
// currentComponent('home'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
this.bind('mycustom-trigger', function (e, data) {
this.redirect('/'); // force redirect
});
this.get('/about', function (evt) {
// currentComponent('about'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run();
// I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
$('.navbar-collapse').click(function () {
app.trigger('mycustom-trigger', app);
});
Please read more about events and routing in sammy.js
Good luck :)
An easier and cleaner way to force the route to reload is to call the Sammy.Application refresh() method:
import { sammyApp } from '../mySammyApp';
const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
sammyApp.refresh();
else {
window.location.hash = url;
}

Call Javascript After Saving Calendar Item

I am having a script as below:-
function getColorValue(aId,atitle) {
try{
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle('Item type');
var oListItem = oList.getItemById(parseInt(aId));
clientContext.load(oListItem);
clientContext.executeQueryAsync(function () {
var listItem = oListItem;
var colorname = listItem.get_item('Color_x0020_Name');
if (typeof colorname != 'undefined') {
if (colorname != null) {
$("div[title$='" + atitle + "']").css("background-color", colorname);
}
}
}, onColorQueryFail);
}
catch(e){
}
}
I need to call this script each time after a SharePoint Calendar Item is created.
Can anyone help?
The following JavaScript example demonstrates how to register event that will be triggered after Calendar item is created:
//custom handler that will be triggered after Calendar item is created
function onEventCreated(){
alert('Event has been created...');
}
function registerCalendarEventOnItemCreated(event)
{
var currentCtx = getCurrentContextInfo();
var calContainer = SP.UI.ApplicationPages.CalendarInstanceRepository.lookupInstance(currentCtx.ctxId);
for(var name in calContainer) {
if(calContainer.hasOwnProperty(name)) {
var p = calContainer[name];
if(p instanceof SP.UI.ApplicationPages.CalendarNewFormDialog) {
p.get_events().addHandler("newitemcreated",event);
}
}
}
}
//get current context info
function getCurrentContextInfo()
{
var currentListId = new SP.Guid(_spPageContextInfo.pageListId);
for(var ctxKey in g_ctxDict){
var curCtx = g_ctxDict[ctxKey];
if(curCtx.listName == currentListId.toString()){
return curCtx;
}
}
return null;
}
//register Calendar events
$('body').on('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});
Has been tested against SharePoint 2013/Online
In your case the function getColorValue could be invoked from onEventCreated, for example:
function onEventCreated(){
getColorValue (id,title);
}
How to apply changes
Switch the page into Edit mode
Add Script Editor webpart into page.
Put the specified code by wrapping it using script tag code into the Script Editor, for example: <script type="text/javascript">{JavaScipt code goes here}</script>
Save the page
Results
Create an Event Receiver with List Item Events for type and Calendar for Source then check 'An item is being added' in handling the event.
Then in the code behind of your Event Receiver:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//Call your function through this
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);
}
Hope that helps :)
I know this is an old question, but there is an issue with the solution given.
I had a requirement to implement an workaround to the missing Resource Reservation feature in Sharepoint online. It was not possible to use an approach more suitable to the Modern Experience, due its dependency of Azure (no Azure subscription available for it), so I use Sharepoint API calls to perform the the same functionality of Resource Reservation.
To use the Sharepoint API, some Ajax calls were needed. But I observed that two calls were executed for each request.
The point is when you register calendar events, it is needed to attach the click event using one, as seen below, to prevent the click event to be fired more than once.
//register Calendar events
$('body').one('click', 'div#AsynchronousViewDefault_CalendarView', function() {
registerCalendarEventOnItemCreated(onEventCreated);
});

Google calendar export application error

I am writing a short application for exporting events to Google calendar. (Events are obtained from code processing information from my website.) However, when I click the button, the script I wrote is giving me a strange error. The error I get the first time I click the button is: Uncaught TypeError: Cannot call method 'setApiKey' of undefined. However, the second time I click the button without refreshing the page, the error disappears and the code runs perfectly.
Here is my code, as you can see I defined the api key before setting it:
var exportCalendarToGoogle = function() {
var clientId = '38247913478902437.google#user...';
var scope = 'https://www.googleapis.com/auth/calendar';
var apiKey = 'JDKLSFDIOP109321403AJSL';
var withGApi = function() {
gapi.client.setApiKey(apiKey);
gapi.auth.init(checkAuth);
}
var checkAuth = function() {
gapi.auth.authorize({client_id: clientId, scope: scope, immediate: false}, handleAuthResult);
}
var handleAuthResult = function(authResult) {
if(authResult) {
gapi.client.load("calendar", "v3", exportCalendar);
} else {
alert("Authentication failed: please enter correct login information.");
}
}
//functions to format the calendar json input to Google calendar...
Sounds like gapi has not been fully loaded
http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted
There are two callbacks:
1) In the URL to load the gapi code:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
2) You can also supply a callback function that will let you know when a specific API has loaded:
gapi.client.load('plus', 'v1', function() { console.log('loaded.'); });
I think your problem is 1)

Categories