How to open popup with dropbox-api dropbox-js V2 - dropbox

I'm trying to migrate to dropbox-api v2 in my web application.
Currently I have implementation of opening popup window where user connects to his/her dropbox and I get token. Which I use to get access to files user selected in Dropbox.chooser in later steps.
But I'm having hard time to find the solution for this. I have link to all migration documents dropbox has, but there is not any word about what is the equivalent of client.authenticate() and Dropbox.AuthDriver.Popup() ?

Common Dropbox!!! I just found this issue posted in GitHub for dropbox-sdk-js, and the answer that they don't have this functionality in V2 :( it is really disappointing, i need to implement all staff myself:
https://github.com/dropbox/dropbox-sdk-js/issues/73#issuecomment-247382634
Updated
I have implemented my solution and would like to share if someone will need.
To open a popup window I use following code:
window.open(dropbox.getAuthenticationUrl("MY REDIRECT URL"), 'DropboxAuthPopup', 'dialog=yes,dependent=yes,scrollbars=yes,location=yes')
window.addEventListener('message',function(e) {
if (window.location.origin !== e.origin) {
// Throw error
} else {
// e.data Is what was sent from redirectUrl
// e.data.access_token is the token I needed from dropbox
}
},false);
Then on my page, which I specify dropbox to redirect, i put:
window.addEventListener('load', function() {
var message = parseQueryString(window.location.hash)
window.location.hash = '';
opener = window.opener
if (window.parent != window.top) {
opener = opener || window.parent
}
opener.postMessage(message, window.location.origin);
window.close();
})
Example of parseQueryString can be found from dropbox-sdk-js examples

Related

Not geting token Google Oauth

I'm trying to use google API for login but for some reason both $_GET["code"] and $this->request->getVar('code') are empty and I can't fetch my token because of it. I have tried $_GET["code"] instead of $this->request->getVar('code') but nothing is working:
Error Image second image
I was following this video tutorial: click here
public function signup_with_gmail() {
require_once APPPATH.'Libraries\vendor\autoload.php';
$google_client = new \Google_Client();
//$google_client->setApplicationName("pharma");
$google_client->setClientId('clientID');
$google_client->setClientSecret('SECRET');
$google_client->setRedirectUri('http://localhost/pharma/User/sign_in');
$google_client->addScope('email');
$google_client->addScope('profile');
print_r($this->request->getVar('code') === NULL);
print_r($_GET['code']);
if ($this->request->getVar('code') != NULL) {
$token = $google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
if(!$token['error']){
$google_client->setAccessToken($token['access_token']);
$session->set('access_token', $token['access_token']);
//now get profile data create another object
$google_service = new \Google_Service_Oauth2($google_client);
$data = $google_service->userinfo->get();
print_r($data);
}
}
print_r($data);
}
The code in $this->request->getVar('code') will be generated only when you will hit the URL created using $google_client->createAuthUrl();
So, you can do it like this...
In Controller write
$data['loginButton'] = $google_client->createAuthUrl();
Pass this $data['loginButton'] to the view in the anchor tag for the Sign in with Google button.
Now when you will click on the Sign in with Google button it will redirect back to the same localhost.com/login URL but this time you will have the code in the URL. So you can fetch it with $this->request->getVar('code') and follow the rest of the process.
Please make sure all the detail like ClientId & ClientSecret is correct
And update to the latest "google/apiclient": "^2.10"

Google Funding Choices Form Won't Load

I'm trying out Google Funding Choices, but I can't even get the base form to load, following Google's instructions to the letter. I've set up the relevant site and its consent details, configured a basic message for Ad Blocking, pasted in the code snippet output from the deployment instructions in the FC console, and I placed the following from Google's FC documentation before the FC tag, just to try getting the form to load, but this isn't working (and I'm using the url params ?fc=alwaysshow&fctype=ab):
<script>
// Make sure that the properties exist on the window.
window.googlefc = window.googlefc || {};
window.googlefc.callbackQueue = window.googlefc.callbackQueue || [];
// To guarantee functionality, this must go before the FC tag on the page.
googlefc.controlledMessagingFunction = (message) => {
user.isSubscriber().then(
function (isSubscriber) {
// Do not show the message if a user is a subscriber.
if (isSubscriber) {
message.proceed(false);
} else {
message.proceed(true);
}
}
)};
</script>
Thanks in advance for any guidance

Google Cloud Endpoints - Switch user / Require sign in again

When you authenticate with Google Cloud Endpoints if there is several Google Accounts signed in,that have already given your app permission, it simply chooses the default account, just like Gmail would do.
1) Gmail has the ability to switch Google Accounts in the top right corner. How would I achieve something similar?
2) Can you require a user to sign into their Google account again even if they are already signed in? Similar to when a user goes to change their account settings.
I've found a way, but it is a bit sad that this feature is not included (or not documented) in gapi.auth.authorize.
Anyway, if you open the authorization popup manually, and then process the resulting token, you can pass additional parameters such as prompt=select_account, which will allow the user to select their account.
Here's a code example. With popup blocking, you will have to call this function in an onclick event for the popup not to be blocked.
As such, the code is not really production-ready. We do not manage cases such as when the user refuses to give his consent, and we do not pass extra token information such as the expiration time.
var switchUserAccount = function (callback) {
var popup = window.open("https://accounts.google.com/o/oauth2/auth?client_id=102862643449-geb89aoann7dj6tsha4mtkhvos5mk01b.apps.googleusercontent.com"
+ "&prompt=select_account"
+ "&scope=https://www.googleapis.com/auth/userinfo.email"
+ "&redirect_uri=https://david-sandbox.appspot.com/autoclose.html"
+ "&access_type=online&response_type=token", "thewindow");
var waitForPopup = function () {
try {
var token = popup.location.hash.substring(14).split("&")[0];
console.log("FOund token !" + token);
if (token == "") {
console.log("Not ready yet")
setTimeout(waitForPopup, 500);
} else {
gapi.auth.setToken({access_token: token});
popup.close();
callback();
}
}
catch (e) {
console.log("Not ready yet, exception")
setTimeout(waitForPopup, 500);
}
};
waitForPopup();
}

Get tagged photo without access token

I have some problem on this. Can I get public tagged photo from Instagram api without getting any code or access token?
Please share any link for reading because I cannot found any. I feel it is less knowledge about Instagram api on web.
Thanks!
You can pull public media by tag without authentication.
Take a look at the API documentation for the get /tags/tag-name/media/recent endpoint. Here's the URL: http://instagram.com/developer/endpoints/tags/#get_tags_media_recent
The documentation can be confusing, it shows using an access_token for this endpoint in the example, but it is not required. You will need to register an application and get a client ID.
I use MeteorJS and call a method server side that returns essentially the 'view source' of the instagram page. So if you can run a server side scrape on the tag url you will be able to handle the response with what i have below and it will push all the images into an array.
//server side method
Meteor.methods({
'scrapeInst':function(tag){
return Scrape.url('https://www.instagram.com/explore/tags/'+tag+'/')
}})
//client side logic
Meteor.call('scrapeInst',Session.get('params').tag,function(err,resp){
var theInstResp = resp;
cleanOne = resp.replace(/>|window._sharedData = |;</|;|#47;|<|/g,'').split('script')
var splitter = cleanOne[22].split(',');
var theArr = [];
_.each(splitter,function(e){
var theFinal = {};
var theS = e.split(":");
if(theS[0].replace(/"| |/g,'') === "display_src"){
theFinal[theS[0].replace(/"| |/g,'')] = theS[2].replace(/%22/g,'');
theArr.push(theFinal)
}
});
Session.set('photos',theArr);
setTimeout(function(){
Session.set('loading',false)
},1000)
})

How do I get data from a background page to the content script in google chrome extensions

I've been trying to send data from my background page to a content script in my chrome extension. i can't seem to get it to work. I've read a few posts online but they're not really clear and seem quite high level. I've got managed to get the oauth working using the Oauth contacts example on the Chrome samples. The authentication works, i can get the data and display it in an html page by opening a new tab.
I want to send this data to a content script.
i'm having a lot of trouble with this and would really appreciate if someone could outline the explicit steps you need to follow to send data from a bg page to a content script or even better some code. Any takers?
the code for my background page is below (i've excluded the oauth paramaeters and other )
` function onContacts(text, xhr) {
contacts = [];
var data = JSON.parse(text);
var realdata = data.contacts;
for (var i = 0, person; person = realdata.person[i]; i++) {
var contact = {
'name' : person['name'],
'emails' : person['email']
};
contacts.push(contact); //this array "contacts" is read by the
contacts.html page when opened in a new tab
}
chrome.tabs.create({ 'url' : 'contacts.html'}); sending data to new tab
//chrome.tabs.executeScript(null,{file: "contentscript.js"});
may be this may work?
};
function getContacts() {
oauth.authorize(function() {
console.log("on authorize");
setIcon();
var url = "http://mydataurl/";
oauth.sendSignedRequest(url, onContacts);
});
};
chrome.browserAction.onClicked.addListener(getContacts);`
As i'm not quite sure how to get the data into the content script i wont bother posting the multiple versions of my failed content scripts. if I could just get a sample on how to request the "contacts" array from my content script, and how to send the data from the bg page, that would be great!
You have two options getting the data into the content script:
Using Tab API:
http://code.google.com/chrome/extensions/tabs.html#method-executeScript
Using Messaging:
http://code.google.com/chrome/extensions/messaging.html
Using Tab API
I usually use this approach when my extension will just be used once in a while, for example, setting the image as my desktop wallpaper. People don't set a wallpaper every second, or every minute. They usually do it once a week or even day. So I just inject a content script to that page. It is pretty easy to do so, you can either do it by file or code as explained in the documentation:
chrome.tabs.executeScript(tab.id, {file: 'inject_this.js'}, function() {
console.log('Successfully injected script into the page');
});
Using Messaging
If you are constantly need information from your websites, it would be better to use messaging. There are two types of messaging, Long-lived and Single-requests. Your content script (that you define in the manifest) can listen for extension requests:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == 'ping')
sendResponse({ data: 'pong' });
else
sendResponse({});
});
And your background page could send a message to that content script through messaging. As shown below, it will get the currently selected tab and send a request to that page.
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: 'ping'}, function(response) {
console.log(response.data);
});
});
Depends on your extension which method to use. I have used both. For an extension that will be used like every second, every time, I use Messaging (Long-Lived). For an extension that will not be used every time, then you don't need the content script in every single page, you can just use the Tab API executeScript because it will just inject a content script whenever you need to.
Hope that helps! Do a search on Stackoverflow, there are many answers to content scripts and background pages.
To follow on Mohamed's point.
If you want to pass data from the background script to the content script at initialisation, you can generate another simple script that contains only JSON and execute it beforehand.
Is that what you are looking for?
Otherwise, you will need to use the message passing interface
In the background page:
// Subscribe to onVisited event, so that injectSite() is called once at every pageload.
chrome.history.onVisited.addListener(injectSite);
function injectSite(data) {
// get custom configuration for this URL in the background page.
var site_conf = getSiteConfiguration(data.url);
if (site_conf)
{
chrome.tabs.executeScript({ code: 'PARAMS = ' + JSON.stringify(site_conf) + ';' });
chrome.tabs.executeScript({ file: 'site_injection.js' });
}
}
In the content script page (site_injection.js)
// read config directly from background
console.log(PARAM.whatever);
I thought I'd update this answer for current and future readers.
According to the Chrome API, chrome.extension.onRequest is "[d]eprecated since Chrome 33. Please use runtime.onMessage."
See this tutorial from the Chrome API for code examples on the messaging API.
Also, there are similar (newer) SO posts, such as this one, which are more relevant for the time being.