LocalStorage and popup not working on a windows pc - javascript

I'm currently facing a really difficult bug on my code. This code works on my MacOS (on firefox, opera, safari and chrome) and also works on another Windows machine I have. However it doesn't work on a friend's computer using Windows, with Opera, Chrome or Edge.
What the code does is:
A user clicks on a button
I open a popup for a third party website
that redirects me back to my site with a code on the url
I use that code to fetch my server that fetches an api for the user info
I receive that info on the popup and save it to localStorage
The main window detects that there was a store event and displays the user information
The bug can manifest in the following ways:
The popup is force closed (even if no windows.close function is
triggered)
Even if the data is stored in the popup and I can see it
there, it doesn't show up on the main window storage
I have tried postMessage instead of localStorage and it works better than localStorage. Using postMessage the bug doesn't manifest itself using the private mode of Opera on Windows.
I tried using Cookies but they don't fit my use-case because I need to save the user image and it's too big for a cookie.
I also tried opening up a new tab instead of a window and the bug persists.
I have always cleared the cache and localstorage. I also had extensions disabled. Both the main website and the popup are on the same domain and protocol. The diference is the popup that is under /redirect?code=xxxxxxxx
Another weird fact: We had two different branches for this project on git: 'master' and 'develop'. Both published on heroku, and 'develop' had no bug on my friends pc. 'develop' was ahead of 'master' with no conflicts, we merged and the bug appeared on the 'master' website.
page.js (the main window)
function loginButtonAction(event) {
window.open(fenixRequestUserPermissionURL, '_blank', 'width=750,height=675');
fenixLoginButton.classList.add('is-loading');
window.addEventListener('storage', function() {
var userData = JSON.parse(localStorage.getItem('fenix-user'));
registerUser(userData);
localStorage.removeItem('fenix-user');
});
event.preventDefault();
fenixLoginButton.removeEventListener('click', loginButtonAction);
}
fenixLoginButton.addEventListener('click', loginButtonAction);
popup.js (the window to which the first link redirects to)
window.addEventListener('load', function() {
var params = new URL(window.location.href).searchParams;
if (params.has('code')) {
var code = params.get('code');
fetch('/fetchInfo/' + code)
.then(function (response) {
return response.json();
})
.then(function(received) {
localStorage.setItem('fenix-user', JSON.stringify(received));
window.close();
}).catch(function(error) {
console.warn(error);
});
}
});
The bug is silent, there are no errors on any of the consoles. Thank you for reading until here!

Related

Chrome on Android doesn't offer to open PDFs when opened in new tab after a delay

Apologies that this is a long question, I wanted to make sure it was clear what the problem is and, just as importantly, what it isn't - because I know there are a lot of questions that seem related but they don't seem to be about quite the same issue:
The web application we're developing at work needs to open a URL in a new tab when the user presses a particular button, after an API request has completed. The URL in question happens to open a PDF document.
We're aware of the issue with popup blockers, so are opening a blank tab straight away when the button is pressed, then setting the location to the URL a short time later after the API request completes. And this is working fine on desktop browsers as well as on Safari on iPad.
But there is a peculiar problem with Chrome on Android - at least we have observed the problem on Galaxy tablet versions 6 and 7. I'm aware that for some reason Chrome on Android does not have a built-in PDF viewer - however, it seems that accessing the PDF should trigger the OS to ask the user which app they want to use to view the PDF, and we are OK with that. What we do not want - but what is happening at the moment - is the PDF simply getting downloaded in the background, and the user not being given the option of viewing it directly.
From my research on how browsers handle PDFs, it seems this behaviour is dependent on various response headers - notably Content-Type and Content-Disposition. But we are doing this correctly as far as I know - the Content-Type is application/pdf and there is no Content-Disposition header so it should default to "inline", ie opening up to view rather than downloading. And I have tried adjusting the backend to send this header explicitly, both with and without a filename parameter - with no change in observed behaviour.
I strongly suspect this is a bug with Chrome and/or Android, but I cannot find it clearly reported anywhere. The key thing is that there is a delay in setting the URL - because if I put this directly into the console (which I can do when running browserstack from my desktop; not sure if there's any way to input it into a real device directly):
function test1() {
window.open("url/for/my/pdf");
}
this works fine (the device prompts you with a choice of how to open the PDF)
but not with either
function test2() {
const newTab = window.open();
setTimeout(() => {
newTab.location = "url/for/my/pdf";
}, 1000);
}
or even with this, non-asynchronous, version:
function test3() {
const newTab = window.open();
newTab.location = "url/for/my/pdf";
}
Both test2 and test3 above, when called from the console, result in the PDF being downloaded rather than viewed. And this isn't specific to our endpoints - I've tested it with URLs to various random PDF documents I've found online, and the same behaviour occurs.
So my questions are:
is this a known bug with Chrome or Android?
whatever the answer to 1) above, is there any straightforward workaround which will ensure the user is always prompted to open an application to view the PDF, rather than simply downloading it? (Bearing in mind that we can't avoid the delay between opening the tab and setting the location - or at least this is our preferred way.)
Thanks in advance!

window.open in background.js Chrome BUG ? It's work in unpacked extension not in PROD (published in the store)

I can't figure why my code working in DEV environment, when i publish my code it's not work, and made my Chrome Extension crash, and a message said that my extension is corrupted.
Since the latest update of Chrome (73.0.3683.75), we are not able to do cross site call in the content.js, so i need to open a popup to do what i need to do.
I call from the content.js a method in my background.js to open popup.
Content.js
chrome.runtime.sendMessage(extensionID, { method: "CustomUpload",function(){
});
In my background.js script i received the call and open the popup.
case "CustomUpload":
var w = window.open("/upload.html", "name", 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=250', false);
w.focus();
w.addEventListener("load", function () {
w.InitializeFileHelper();
}, true);
I don't know why, but it's workin in DEV not in prod. Where i miss something ?
If i activate developper mode, i go get the "extension" and load extension unpackted everything working fine. It's there a bug with chrome ?
%userprofile%\AppData\Local\Google\Chrome\User Data\Default
I do a lot of test and always the same problem.
I try
chrome.windows.create({ url: chrome.extension.getURL("upload.html")})
chrome.tabs.create({ url: chrome.extension.getURL("upload.html") });
window.open(chrome.extension.getURL("/upload.html"));
Always same result, working fine "localally" but when it's published stop working and get a message Extension could be corrupted.
I see the popup show up for 1ms and then close and the extension is need to be repair.
My problem was an image in my "upload.html" file.
My image was in the extension, the path was good, but chrome extension was crash when the image was there. Just remove the image, and the extension working well.
Special thanks to #wOxxOm for is help.

FB.login() fails with "Unsafe JavaScript attempt to initiate navigation for frame" on Android Chrome but not desktop Chrome

I have a Facebook JS SDK login flow here: https://web.triller.co/#/user/login
When the user taps the Facebook button, the following function is executed:
loginFacebook()
{
const fbPromise = new Promise((resolve, reject) => {
FB.login(resp => {
if (resp.authResponse)
{
resolve(resp.authResponse.accessToken);
}
else
{
console.log(resp);
reject(new Error('Facebook login canceled or failed.'));
}
});
});
return fbPromise
.then(accessToken => api.postJson('user/login_facebook', { accessToken }))
.then(this._handleLogin.bind(this));
}
Basically, it calls FB.login(), and expects to receive a valid resp.authResponse. Unfortunately, it doesn't, even after successfully authenticating on the Facebook popup/tab. Instead, we receive { authResponse: undefined, status: undefined } and the following error from the browser:
Unsafe JavaScript attempt to initiate navigation for frame with URL
'https://m.facebook.com/v2.8/dialog/oauth?foo=bar'
from frame with URL 'https://web.triller.co/#/user/login?_k=cmzdb6'.
The frame attempting navigation is neither same-origin with the
target, nor is it the target's parent or opener.
The error occurs immediately after authenticating within the Facebook popup/tab, and it only occurs on Android Chrome. Desktop Chrome (on a Mac) does not show the same error. Safari on iOS does not show the error, either.
Any thoughts on what's going on? Why the difference between Android Chrome and desktop Chrome? Could it have something to do with the hash in the URL?
In desktop this issue can be caused by XFINITY Constant Guard Protection Suite Chrome extension. Disble it and problem will be solved.
In Android, try removing XFINITY or similar security extensions or applications (Norton security antivirus).
https://developer.salesforce.com/forums/?id=906F00000008qKnIAI
I think it fails because of the m.facebook.com/... based on this https://en.wikipedia.org/wiki/Same-origin_policy#Origin_determination_rules (see the case for http://en.example.com/dir/other.html and why it fails). Although it shouldn't based on what I've done with the fb api this is weird, try making a cors request instead as a workaround?
This is a known issue here https://code.google.com/p/android/issues/detail?id=20254.
When the window.open is called without proper arguments, it will not be opened as expected.
It can be overcome by either updating the browser (for client, check the browser version and if old one, force them to update it).
Otherwise (not applicable for you since you can't change the FB function), pass the correct arguments to window.open
Interestingly I only seem to get this when I am using the mobile device simulator in Chrome.
Looking at the source code for the Facebook SDK there is the following line:
url: i.resolve(a.display == "touch" ? "m" : "www") + "/" + d.url,
Now "m" then becomes "m.facebook.com" whereas "www" becomes "www.facebook.com". So it's using a different URL based on whether or not it's touch.
Now they're the same domain anyway, and the connect API is loaded from facebook.net (not .com) so it's not as simple as just being a different domain. However I suspect the issue could be related to this.
In either case when not in mobile device testing mode I don't get the error.

setting onbeforeunload on IE11

I'd like confirmation, should I be able to set onebeforeunload on an opened window in IE11.
Edit: some extra info
The page opening the window is located on a page such as
https://subsub.sub.company.tld/someapp/#/somepage
The window is opening an url like
https://subsub.sub.company.tld/someService/SomeIdentifier?timestamp=214124
As far as I am aware this should be fine?
var pop = window.open("url-on-same-domain");
pop.addEventListener("beforeunload", function() {
//something here
}):
Currently I can't add this listener due to Permissions (as far as I know this shouldn't be an issue on a same-domain environment). It does however have a unverified SSL connection e.g. defect certificate due to dev env.
Error: Permission denied
... some stack which goes back to pop.addEventListener
I also tried setting pop.onbeforeunload = function(){} but this is being ignored.
Anyone who can fill me in on this? We also have an issue on our test environment which is on localhost where attaching the evenListener won't work on IE and Edge.
My problem was caused by the popup opening a PDF File. In IE there is never access to Files opened in a window.
We worked around this by wrapping the file in an iFrame, which might sound nasty, but we needed to be able to display custom messages sometimes so it was OK for us as no other solution was workable.

How do I refresh/reload a Chrome Extension?

I'm developing an extension in Chrome 4 (currently 4.0.249.0) that will show the user's StackOverflow/SuperUser/ServerFault reputation in the status bar. I've designed an options page to get the user's profile IDs and I save them to localStorage and read them well in the extension. It all works great.
The problem is I cannot find a (programmatic) way to refresh the extension upon options saving. I tried calling location.reload(); from the extension page itself upon right clicking it - to no avail. I pursued it further and tried looking at what Chrome's chrome://extensions/ page does to reload an extension, and found this code:
/**
* Handles a 'reload' button getting clicked.
*/
function handleReloadExtension(node) {
// Tell the C++ ExtensionDOMHandler to reload the extension.
chrome.send('reload', [node.extensionId]);
}
Copying this code to my event handler did not help (and yes, I tried replacing [node.extensionId] with the actual code). Can someone please assist me in doing this the right way, or pointing me at a code of an extension that does this correctly? Once done, I'll put the extension and its source up on my blog.
Now the simplest way to make extension to reload itself is to call chrome.runtime.reload(). This feature doesn't need any permissions in manifest.
To reload another extension use chrome.management.setEnabled(). It requires "permissions": [ "management" ] in manifest.
window.location.reload() works for me
I am using chromium 6.x so it might be fixed in newer version
The chrome.send function is not accessible by your extension's javascript code, pages like the newtab page, history and the extensions page use it to communicate with the C++ controller code for those pages.
You can push updates of your extension to users who have it installed, this is described here. The user's application will be updated once the autoupdate interval is hit or when they restart the browser. You cannot however reload a user's extension programmatically. I think that would be a security risk.
I just had this same problem with an extension.
Turns out you can listen for storage changes within background.js using chrome.storage.onChanged and have that perform the refresh logic.
For example:
// Perform a reload any time the user clicks "Save"
chrome.storage.onChanged.addListener(function(changes, namespace) {
chrome.storage.sync.get({
profileId: 0
}, function(items) {
// Update status bar text here
});
});
You could also reload parts of your extension this way by taking the changes parameter into account. chrome.runtime.reload() might be easier, but this has less overhead.
For all future Googlers - the Browser Extension spec now includes runtime.reload() - https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/reload
For Chrome, you might need to use chrome.runtime.reload() (but I'd handle such cases via Mozilla's awesome webextension-polyfill).

Categories

Resources