How to show a popup in chrome extension just on a single condition on OnClick event? - google-chrome-extension

Hi I am in need to show a popup just once during installation of the extension asking for username and a log in button.When the user first clicks on the extension icon,a pop up should appear asking for username.when the user enters his username correctly,and clicks login,the pop up should be closed and then when the user again clicks on the extension icon,it should navigate to a website.What I did is when the user enters his username,it is stored in the localStorage,Each time when the user clicks on the extension icon,it checks for whether there is username in localstorage.if yes,then it should navigate to website otherwise,it should show the popup again.How can this be done?Please help me.
Here is my background.js
chrome.browserAction.onClicked.addListener(function(tab) {
if(!localStorage.username){
chrome.browserAction.setPopup({
popup: "userinfo.html"
});
}
else{//navigate to website }
});
Here the problem is that when the user first clicks on the icon,the pop up appears and the user enters his name and login.Next time when i click it again shows the pop up only.IT is not navigating to the website.Until i reload the extension,it shows only the popup on the onclick event.Anyone please help me.

You could register a listener for the chrome.browserAction.onClicked event that checks if the username is stored in localStorage and:
if it is there navigate to the website.
if it is not there navigate to userinfo.html (either in a new tab or opening a new popu window (using chrome.windows.create()), which enables you to define its location and size).
when submitting the username and password in your userinfo.html page you can store them in localStorage and log the user in.
E.g.:
In background.js:
var myWebsite = 'https://your.domain.goes/here';
var myUserinfo = chrome.extension.getURL('userinfo.html');
chrome.browserAction.onClicked.addListener(function(tab) {
if (localStorage.username) {
/* Navigate to website */
chrome.tabs.create({ url: myWebsite });
} else {
/* Navigate to `userifo.html` */
chrome.tabs.create({ url: myUserinfo });
}
});
chrome.runtime.onMessage.addListener(function(msg, sender) {
if ((msg.action === 'saveCredentials')
&& msg.user && msg.pass) {
/* Store the credentials in localStorage */
localStorage.username = user;
localStorage.password = pass;
/* For a better user-experience, let's
* navigate the user to the website right away */
chrome.tabs.updated(sender.tab.id, { url: myWebsite });
}
});
In userinfo.html's JS:
// ...once the userinfo is "submitted"
var user = ...;
var pass = ...;
chrome.runtime.sendMessage({
action: 'saveCredentials',
user: user,
pass: pass
});

Related

identity.launchWebAuthFlow dont open popup in google chrome extension

I want to use chrome.identity.launchWebAuthFlow like this exemple :
document.getElementById("myButton").addEventListener("click", function() {
chrome.identity.launchWebAuthFlow({
url: "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=https://auth.example.com/callback&scope=openid email",
interactive: false
}, function(redirectUri) {
if (chrome.runtime.lastError) {
// Error handling
console.error(chrome.runtime.lastError.message);
} else {
// Extract the code from the redirect URI
var code = redirectUri.substring(redirectUri.indexOf("code=") + 5);
// Use the code to obtain an access token
// ...
}
});
});
But I have no popup that opens after my event click. And have any error in console or callback.
Any idea ?
I had this issue before, just change interactive from false to true, that will pop up the authentication flow, if you just need to get a new access token without the user having to re-enter the credentials, then you use interactive: false

load last viewed page on chrome extension startup

I'm developing my first chrome extension and I'm stuck with a "session restore" problem. At the begging of the developement when a user log in to my extension and close the popup, when he open the plugin again he had to login again.
I've used chrome.storage.sync to be able to save the session infomation to make the user to be still logged in and if he close the plugin, and his session is still active he will be redirected to the welcome page. But how can I check at the extension's startup in what page of the plugin the user was and bring him back to that page?
For example, if a user is logged and was on the "choose a book" section, how can i make the plugin open at "choose a book" section and not in "welcome" section?
Angular 2 for client side
NodeJs for server side
Consider that the session object is something like:
{
logged: true,
last_section: 'books'
}
When the user visits the books section, save it.
// this code goes inside some listener for visiting a section
chrome.storage.sync.get('session', function (items) {
const session = items.session || {}
session.last_section = 'books'
chrome.storage.sync.set({ session })
})
At the beginning of the popup script, you can simply call chrome.storage.sync.get to get the last session object state.
chrome.storage.sync.get('session', function (items) {
const session = items.session
if (session && session.logged) {
if (session.last_section === 'books') {
// render books section
}
if (session.last_section === 'welcome') {
// render welcome section
}
}
})

Firebase Auth Web: Logout with page reload

I use Firebase with VueJS. Sign-up, sign-in works fine so far but as soon as I reload the page with F5 or load a page with writing to the browsers address bar directly then the auth session is killed, the user isn't signed-in anymore. It works fine as long as I don't reload the page, even if I click route links or get redirected to other pages, the user session keeps alive. It doesn't matter where I reload the page btw.
My login method:
firebase.auth().signInWithEmailAndPassword(this.username, this.password).then(
(user) => {
if (user.emailVerified === false) {
firebase.auth().signOut()
} else {
// redirect to lobby page if user is verified and signed in
this.$router.push('/lobby')
}
},
function(err) {
console.log(err.message)
}
)
You need to call firebase.auth().onAuthStateChanged in order to detect whether a user is logged in.
This method gets invoked in the UI thread on changes in the authentication state:
Right after the listener has been registered
When a user is signed in
When the current user is signed out
When the current user changes
Source
Example usage can be like this:
firebase.auth().onAuthStateChanged(user => {
if (user) {
if (user.emailVerified === false) {
firebase.auth().signOut()
} else {
this.$router.push('/lobby')
}
} else {
// will get to here from a logout event
// this.$router.push('/login')
}
}
Use this in your main.js file:
firebase.auth().onAuthStateChanged(() => {
if (!app) {
app = createApp(App).use(store).use(router).mount('#app')
}})
Firebase will run before Vue app is created.

Chrome extension: match opened tab to loaded tab in background.js

I have a Chrome extension. I need to pass a variable to the tab that is opened, and then have that variable be available when the tab's webpage has completed loading. I need to be able to uniquely match the opened tab with the loaded tab.
chrome.browserAction.onClicked.addListener(function(tab) {
url = "my_url";
unique_id = "some id"; // I need to pass this on
chrome.tabs.create({ url: url }, function(tab){});
// I cannot use any global vars because this function actually loops and opens lots of tabs.
});
// Called when page has finished loading
chrome.webNavigation.onCompleted.addListener(function(tab) {
if(tab.frameId == 0){
// I need to identify the tab (unique_id) that was created in chrome.browserAction.onClicked.addListener()
// tab.url won't work because it's different if the orginal url was redirected
}
});
Tabs have tab IDs which are unique within a browser session.
chrome.browserAction.onClicked.addListener(function(tab) {
url = "my_url";
chrome.tabs.create({ url: url }, function(tab){
unique_id = tab.id; // I need to pass this on
});
});
// Called when page has finished loading
chrome.webNavigation.onCompleted.addListener(function(details) {
if(details.frameId == 0){
unique_id = details.tabId;
}
});

Safari does not reopen page after Facebook authentication on iPhone

I'm working on a responsive website that require the user to authenticate with Facebook.
I've set up the Facebook JS SDK, and the login and login-success callback. The setup I have works great on desktop, but on iPhone (seems to work on iPad!) I'm having an issue I am yet to resolve.
When tapping the Login button, the user is brought to a new tab that asks the user to log in. After the user has entered his/her credentials, the tab is closed, but Safari does not reopen my page. Instead, Safari sits in the "tab selection" screen with my page highlighted. The user has to explicitly re-open my page by tapping the tab. When tapping the tab, it doesn't seem to fire the authResponseChange consistently.
Please note that if I make sure that Safari on iPhone has no tabs open except my page, then I am automatically directed back to it (as expected by the Safari app's design) and the site functions correctly.
<div id="fb-root"></div>
<script>
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/all.js', function() {
FB.init({
appId : 'xxx',
xfbml : true,
status : true,
cookie : true
});
});
});
$("#login_button").bind("vclick", function() {
// Require explicit login
FB.Event.subscribe("auth.authResponseChange", function(response) {
if (response.status === "connected") {
// Perform API calls and display more of the page ...
// $.get("https://graph.facebook.com/me/friends?access_token=")
// FB.api("/me/friends", function(data) {});
}
});
FB.login(function(response) {}, {scope: 'email,friends_birthday,friends_hometown'});
});
</script>

Resources