Getting chrome.getAuthToken to work inside a script - google-chrome

I'm building a Chrome extension that retrieves data from a user's Google Drive and inserts it into an arbitrary page. I've gotten the OAuth to work, but I can't seem to get access to the token (which I can see is set via chrome://identity-internals).
The issue here is that when the Chrome extension nav bar button is clicked, I fire a request to execute test.js. test.js apparently has no concept of chrome.identity, but it needs that information to make an XHR request. I've tried
Storing the auth token in localStorage so that test.js can retrieve it (no luck)
Nesting the test.js inside the AuthToken request (not sure how to actually pass the variable into the file and retrieve it).
Are there any ideas?
Thank you in advance!
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
// This works
alert(token);
// This doesn't work
localStorage.setItem("authtoken", token);
});
chrome.tabs.executeScript(tab.id, {
// This file needs access to the authtoken
// but within test.js, chrome.identity is undefined.
"file": "test.js"
}, function () {
});
});

localStorage (effectively it's window.localStorage) is stored per origin (scheme + hostname + port number), and extensions have their own one in privileged components that can access restricted chrome.* API (some are listed as exceptions in content scripts docs), namely popup and background/event page, options, and other pages with a URL like chrome-extension://abc..... (abc... is an extension ID).
localStorage of a web page belongs to its own origin such as https://www.google.com.
Content scripts run in the context of web page, so they can't access extension's localStorage directly. They see localStorage of their web page's origin only.
Solution 1: use another executeScript to set a variable that will be used by the content script injected from a file:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.tabs.executeScript(tab.id, {
code: 'var token=' + JSON.stringify(token) + ';'
}, function() {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
});
});
});
});
JSON-serialization is used in order not to bother escaping special characters and be able to pass objects.
Solution 2: use messaging API to pass data once the content script is injected:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
chrome.tabs.sendMessage(tab.id, {token: token});
});
});
});
content script:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.token) {
document.getElementById('token').textContent = msg.token;
//nowYouCanProcessToken(msg.token);
}
});
Solution 3: use chrome.storage API accessible both from a content script and the abovementioned privileged parts of an extension.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.storage.local.set({token: token}, function() {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
});
});
});
});
content script:
chrome.storage.local.get('token', function(data) {
if (data.token) {
document.getElementById('token').textContent = data.token;
//nowYouCanProcessToken(data.token);
}
});

Related

PWA: Chrome warning "Service worker does not have the 'fetch' handler"

I'm currently unsuccessfully trying to make my PWA installable. I have registered a SertviceWorker and linked a manifest as well as I am listening on the beforeInstallPromt event.
My ServiceWorker is listening to any fetch event.
My problem is, that the created beforeInstall banner is just being shown on Chrome desktop but on mobile I get a warning in Chrome inspection tab "Application" in the "Manifest" section:
Installability
Service worker does not have the 'fetch' handler
You can check the message on https://dev.testapp.ga/
window.addEventListener('beforeinstallprompt', (e) => {
// Stash the event so it can be triggered later.
deferredPrompt = e;
mtShowInstallButton();
});
manifest.json
{"name":"TestApp","short_name":"TestApp","start_url":"https://testapp.ga/loginCheck","icons":[{"src":"https://testapp.ga/assets/icons/launcher-ldpi.png","sizes":"36x36","density":0.75},{"src":"https://testapp.ga/assets/icons/launcher-mdpi.png","sizes":"48x48","density":1},{"src":"https://testapp.ga/assets/icons/launcher-hdpi.png","sizes":"72x72","density":1.5},{"src":"https://testapp.ga/assets/icons/launcher-xhdpi.png","sizes":"96x96","density":2},{"src":"https://testapp.ga/assets/icons/launcher-xxhdpi.png","sizes":"144x144","density":3},{"src":"https://testapp.ga/assets/icons/launcher-xxxhdpi.png","sizes":"192x192","density":4},{"src":"https://testapp.ga/assets/icons/launcher-web.png","sizes":"512x512","density":10}],"display":"standalone","background_color":"#ffffff","theme_color":"#0288d1","orientation":"any"}
ServiceWorker:
//This array should NEVER contain any file which doesn't exist. Otherwise no single file can be cached.
var preCache=[
'/favicon.png',
'/favicon.ico',
'/assets/Bears/bear-standard.png',
'/assets/jsInclude/mathjax.js',
'/material.js',
'/main.js',
'functions.js',
'/material.css',
'/materialcolors.css',
'/user.css',
'/translations.json',
'/roboto.css',
'/sw.js',
'/'
];
//Please specify the version off your App. For every new version, any files are being refreched.
var appVersion="v0.2.1";
//Please specify all files which sould never be cached
var noCache=[
'/api/'
];
//On installation of app, all files from preCache are being stored automatically.
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(appVersion+'-offline').then(function(cache) {
return cache.addAll(preCache).then(function(){
console.log('mtSW: Given files were successfully pre-cached')
});
})
);
});
function shouldCache(url) {
//Checking if url is market as noCache
var isNoCache=noCache.includes(url.substr(8).substr(url.substr(8).indexOf("/")))||noCache.includes((url.substr(8).substr(url.substr(8).indexOf("/"))).substr(0,(url.substr(8).substr(url.substr(8).indexOf("/"))).indexOf("?")));
//Checking of hostname of request != current hostname
var isOtherHost=url.substr(8).substr(0,url.substr(8).indexOf("/"))!=location.hostname&&url.substr(7).substr(0,url.substr(7).indexOf("/"))!=location.hostname;
return((url.substr(0,4)=="http"||url.substr(0,3)=="ftp") && isNoCache==false && isOtherHost==false);
}
//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
//Trying to answer with "online" version if fails, using cache.
event.respondWith(
fetch(event.request).then(function (response) {
if(shouldCache(response.url)) {
console.log('mtSW: Adding file to cache: '+response.url);
caches.open(appVersion+'-offline').then(function(cache) {
cache.add(new Request(response.url));
});
}
return(response);
}).catch(function(error) {
console.log( 'mtSW: Error fetching. Serving content from cache: ' + error );
//Check to see if you have it in the cache
//Return response
//If not in the cache, then return error page
return caches.open(appVersion+'-offline').then(function (cache) {
return cache.match(event.request).then(function (matching) {
var report = !matching || matching.status == 404?Promise.reject('no-match'): matching;
return report
});
});
})
);
})
I checked the mtShowInstallButton function. It's fully working on desktop.
What does this mean? On the Desktop, I never got this warning, just when using a handheld device/emulator.
Fetch function is used to fetch JSon manifest file. Try reading google docs again.
For adding PWA in Mobile you need manifest file to be fetched which is fetched using service-worker using fetch function.
Here is the code :
fetch('examples/example.json')
.then(function(response) {
// Do stuff with the response
})
.catch(function(error) {
console.log('Looks like there was a problem: \n', error);
});
for more about fetch and manifest try this.

how to change the popup content based on the current url extension page action

am new in creating chrome extensions, I'm developing an extension page action it works in certain urls, I would like to put different text in the popup for each url, i can do it? please help me.
My background.js is thus
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (~tab.url.indexOf('url1.com.br')) {
chrome.pageAction.show(tabId);
}
if (~tab.url.indexOf('url2.com.br')) {
chrome.pageAction.show(tabId);
}
});
OK. First of all, to show page_action icon on specific URLs you can use declarative content.
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's on a specific URL
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'url1.com.br' },
}),
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'url2.com.br' }
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
Don't forget adding a permission for declarative content in manifest.json. Another thing is different texts for different urls.
popup.js
chrome.tabs.query({'active': true, 'currentWindow': true}, function (tabs) {
var dynamicText = "You are here;"+ tabs[0].url;
document.getElementById("textbox").value = dynamicText ;
});
This sample gets the currentWindow's URL and insert it into the element that has textbox id. I hope samples are enough to solve the problem.

Stop chrome extension from executing based on condition

Chrome extension that I'm developing requires users to authenticate with Gmail account.
However, if a user doesn't want to authorize, I've stopped the authorization window from appearing. However, some background scripts seem to be running. How do I make sure that the extension stops functioning completely?
You must initiate your extension in a callback called when the user is authenticated. For example, using oAuth2:
function onAuthorized() {
var url = 'https://www.googleapis.com/oauth2/v1/userinfo';
var request = {
'method': 'GET',
'parameters': {
'alt': 'json'
}
};
// Declare the callback
oauth.sendSignedRequest(url, callback, request);
};
and the callback:
function callback(resp, xhr) {
// ... Process text response ...
}).done(function (data) {
// Your used is authenticated...
// ==>Init your extension HERE
});
}
A background page with "persistent": false will be unloaded after a few seconds of inactivity. Stop doing work and the right thing will happen.

Cannot view source HTML on Chrome

I am unable to view the HTML content of web pages when I view source in Google Chrome's dev tools. For example, if I view the source of https://stackoverflow.com/help, the only content I can see is as follows.
<script>
$('#herobox li').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
window.location.href = '/about';
});
$('#tell-me-more').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
});
$('#herobox #close').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("hero.action", { hero_action_type: "minimize" }, true);
});
$.cookie("hero", "mini", { path: "/" });
$.ajax({
url: "/hero-mini",
success: function (data) {
$("#herobox").fadeOut("fast", function () {
$("#herobox").replaceWith(data);
$("#herobox-mini").fadeIn("fast");
});
}
});
return false;
});
</script>
I'm not sure if I've inadvertently changed a setting in Chrome, but any help would be greatly appreciated.
I'm using chrome Version 29.0.1547.76.
I have disabled all extensions.
I tried this using a new profile with the same effect.
I'm not behind a proxy.
If you open the DevTools after loading the page, the content of the items listed on the Resources tab may not be populated. This is also true of network requests on the Network tab. To see the fully populated resources on the Resources tab, first open the DevTools, then refresh the page, or navigate to the desired page with the DevTools open. Now select the html resource and it should be populated.

FineUploader OnComplete method not firing

So, I'm using FineUploader 3.3 within a MVC 4 application, and this is a very cool plugin, well worth the nominal cost. Now, I just need to get it working correctly.
I'm pretty new to MVC and absolutely new to passing back JSON, so I need some help getting this to work. Here's what I'm using, all within doc.ready.
var manualuploader = $('#files-upload').fineUploader({
request:
{
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
},
callbacks: {
onComplete: function(id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
}
}
}
EDIT: I had been using Internet Explorer 9, then switched to Chrome, Firefox and I can upload just fine. What's required for IE9? Validation doesn't work, regardless of browser.
Endpoint fires, and file/parameters are populated, so this is all good! Validation doesn't stop a user from selecting something outside of this list, but I can work with this for the time being. I can successfully save and do what I need to do with my upload, minus getting the OnComplete to fire. Actually, in IE, I get an OPEN/SAVE dialog with what I have currently.
Question: Are the function parameters in onComplete (id, filename, responseJSON) getting populated by the return or on the way out? I'm just confused about this. Does my JSON have to have these parameters in it, and populated?
I don't do this (populate those parameters), and my output method in C# returns JsonResult looking like this, just returning 'success' (if appropriate):
return Json(new { success = true });
Do I need to add more? This line is after the saving takes place, and all I want to do is tell the user all is good or not. Does the success property in my JSON match up with the responseJSON.success?
What am I missing, or have wrong?
Addressing the items in your question:
Regarding restrictions inside of the "select files" dialog, you must also set the acceptFiles validation option. See the validation option section in the readme for more details.
Your validation option property in the wrong place. It should not be under the request property/option. The same is true for your text, multiple, and callbacks options/properties. Also, you are not setting your callbacks correctly for the jQuery plug-in.
The open/save dialog in IE is caused by your server not returning a response with the correct "Content-Type" header. Your response's Content-Type should be "text/plain". See the server-side readme for more details.
Anything your server returns in it's response will be parsed by Fine Uploader using JSON.parse when handling the response client-side. The result of invoking JSON.parse on your server's response will be passed as the responseJSON parameter to your onComplete callback handler. If you want to pass specific information from your server to your client-side code, such as some text you may want to display client-side, the new name of the uploaded file, etc, you can do so by adding appropriate properties to your server response. This data will then be made available to you in your onComplete handler. If you don't have any need for this, you can simply return the "success" response you are currently returning. The server-side readme, which I have linked to, provides more information about all of this.
To clarify what I have said in #2, your code should look like this:
$('#files-upload').fineUploader({
request: {
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
});