How do I refresh/reload a Chrome Extension? - javascript

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).

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!

Javascript redirect not working in Edge browser when opened with android ActionView intent, but working after manual reload

Situation
In our Android app (Xamarin), we open a web page using an ActionView intent. The code looks like this:
Intent intent = new Intent((string)Intent.ActionView, Android.Net.Uri.Parse(args.url));
intent.AddFlags(ActivityFlags.NewTask);
The opened page at some point does a JS redirect, with a line like this:
window.location = '...';
We tried many different variations of that line, including window.location.href = '...', window.location.assign('...'); and some more. All show the same behavior.
Problem
This has worked fine for years now, in all browsers - but now we ran into a problem, when the browser on the android device is the Edge browser:
When the browser tab is initially opened by the intent, the window.location = '...' line in Javascript is just ignored by the browser. No error message - just ignored.
However, if that same browser tab with exactly the same URL is opened manually (either by reloading or by copying and pasting the URL), the JS redirect is executed just fine.
Question
How do we fix this, how do we make the JS redirect reliably work?
My guess is that we are running into a security feature, which prevents JS redirects in browser tabs that the user has never interacted with.
Is there something (maybe an intent flag?) to circumvent this? We already tried the flag GrantWriteUriPermission, but it did not help.
Possible duplicates
Android Browser Facebook Redirect Does Not Always Trigger Intent for URL :
The proposed situation of setting the URL on a link and faking a click on it did not work.
Microsoft Edge security
Microsoft Edge recently fixed an issue regarding XSS Targeting Non-Script Elements (June 24, 2021).
The vulnerability was found by two researcher when they visited a website in another language via the Microsoft Edge browser and attempted to translate the page. The goal of the recent fix by Microsoft is to avoid vulnerability regarding accessing dynamically to a content from a third party application and specifically in the case of browser redirection. They need to act quickly because the vulnerability is quite huge.
In order to mitigate a large class of potential cross-site scripting issues, the Microsoft Edge Extension system has incorporated the general concept of Content Security Policy (CSP)
Ok, but ... is there any solution?
Maybe you can find a solution to solve your issue here, in particular the part concerning the <button onclick="...">.
Inline code is considered harmful in concept of CSP and microsoft recommend some good practices :
1 - The clickHandler definition must be moved into an external JavaScript
2 - The inline event handler definitions must be rewritten in terms of addEventListener and extracted into your external js file. If you are currently starting your program using code like <body onload="main();">, consider replacing it by hooking into the DOMContentLoaded event of the document, or the load event of the window, depending on your requirements. Use the former, since it generally triggers more quickly.
3 - Function inside onclick call must be rewritten to avoid converting the string of function into JavaScript for running.
The code exemple of the external .js file cited in the documentation look like this :
function awesome() {
// Do something awesome!
}
function totallyAwesome() {
// do something TOTALLY awesome!
}
function awesomeTask() {
awesome();
totallyAwesome();
}
function clickHandler(e) {
setTimeout(awesomeTask, 1000);
}
function main() {
// Initialization work goes here.
}
// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click',
clickHandler);
main();
});
Hope it's helps

Facebook app browser debugging [duplicate]

I'm developing website with a lot of HTML5 and CSS3 features. I'm also using iframe to embed several content on my website. It works fine if I open it using Chrome/Firefox/Safari mobile browser. However, if I share on facebook (post/page) and I opened it up with Facebook application with Facebook Internal Browser, my website is messed up.
Is there any tools or way to debug on Facebook Browser? Thanks.
This is how you can do the debugging yourself. It's painful, but the only way I've come across so far.
tl;dr Get the Facebook App loading a page on your local server so you can iterate quickly. Then print debug statements directly to the page until you figure out what is going on.
Get a link to a page on your local server that you can access on your mobile device (test in mobile safari that it works). See this to find out your local IP address How do you access a website running on localhost from iPhone browser. It will look something like this
http://192.xxx.1.127:3000/facebook-test
Post that link on your Facebook page (you can make it private so your friends aren't all like WTF?)
Click the posted link in the Facebook mobile App and it will open up in Facebook's mobile browser
Since you don't have a console, you basically need to print debug statements directly to the page so it is visible. Put debug statements all over your code. If your problems are primarily related to CSS, then you can iteratively comment out stuff until you've found the issue(s) or print the relevant CSS attributes using JavaScript. Eg something like (using JQuery)
function debug(str){$('body').append("<br>"+str);}
Quite possibly the most painful part. The Facebook browser caches very aggressively. If you are making changes and nothing has happened, it's because the content is cached. You can sometimes resolve this by updating the URLs, eg /facebook-test-1, /facebook-test-2, or adding dummy parameters eg /facebook-test?dummy=1. But if the changes are in external css or js sheets it sometimes will still cache. To 100% clear the cache, delete the Facebook App from your mobile device and reinstall.
The internal browser the Facebook app uses is essentially a uiWebView. Paul Irish has made a simple iOS app that lets you load any URL into a uiWebView which you then can debug using Safari's Developer Tools.
https://github.com/paulirish/iOS-WebView-App
I found a way how to debug it easier. You will need to install the Ghostlab app (You have a 7-day free trial there, however it's totally worth paying for).
In Ghostlab, add the website address (or a localhost address) you want to debug and start the session.
Ghostlab will generate a link for access.
Copy that link and post it on Facebook (as a private post)
Open the link on mobile and that's it! Ghostlab will identify you once you open that link, and will allow you to debug the page.
For debugging, you will have all the same tools as in the Chrome devtools (how cool is that!). For example, you can tweak CSS and see the changes applied live.
If you want to debug a possible error, you can try to catch it and display it.
Put this at the very top of your code:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
alert(message);
}
}
(Source: MDN)
This will catch and alert your errors.
Share a link on Facebook (privately), or send yourself a message on Facebook Messenger (easier). To break the cache, create a new URL every time, e.g. by appending a random string to the URL.
Follow the link and see if you can find any errors.
With help of ngrok create temporary http & https adress instead of your ordinary localhost:3000(or other port) and you could run your app on any devices. It is super easy to use.
and as it was written above all other useful information you should write somewhere inside div element (in case of React I recommend to put onClick on that div with force update or other function for getting info, sometimes it helps because JS in FB could be executed erlier than your information appears). Keep in mind that alerts are not reliable, sometimes they are blocked
bonus from ngrok that in console you will see which files was
requested and response code (it will replace lack of network tab)
and about iFrame.If you use it on other domain and you rely on cookies - you should know that facebook in-app browser blocks 3rd party cookies
test on Android and iOS separately because technicaly they use different browsers

Angular GET request error, but only on safari iOS

I'm building a website using WordPress as a backend, and AngularJS as the frontend. I'm using the WordPress JSON API to get my data to the front-end.
https://wordpress.org/plugins/json-api/
The problem
I'm using AngularJS to get my data from the WordPress JSON API. I have created the following service:
this.getPage = function ( slug ) {
return $http.get('wordpress/api/get_page/?slug=' + slug)
}
I use this service in my controller to get the current page like this:
HTTPService.getPage('home')
.success(function ( data ) {
$scope.page = data.page;
console.log(arguments);
})
.error( function () {
console.log(arguments);
})
This is working fine in all browsers, except for Safari on iOS. On Safari on iOS I get the following response when I log the error arguments:
This is the safari debugger which showed when I connected my iPhone to my Mac. The error response which I get is error code 0..
What I have tried so far
I have set Access-Control-Allow-Origin "*" in the .htaccess file, but this doesn't seem to work. The request is done on the same domain with a relative URL, so I don't think that this is the problem.
So, does anyone know why this is not working on Safari (iOS)?
EDIT
Some extra information as requested:
I'm pretty sure that this is due to the fact that Safari is the only browser that has the policy of blocking "3rd party cookies and other website data" by default. Actually, this issue shouldn't be exclusive of Safari iOS, it should also happen with Safari on your OSX. I'm pretty sure that if it's not happening in your MacBook is because one day you changed the default settings of the "Privacy".
You can try this, open Safari, go to "preferences" and under the tab "Pricacy" check if you have the option: "Block cookies and other website data" set to "From third parties and advertisers". This is the first, and the default option in the modern versions of Safari.
In your MacBook it will look like this:
And in iOS it will look like this:
Just to confirm that this is in fact what's causing your issue: change this setting to "Never", clear the cache and try to reproduce that problem again. I'm quite confident that you won't be able to reproduce it.
Now, if you set it back to "Block cookies and other website data: From third parties and advertisers" and you first clear the cache, you will have that problem again (with either iOS or OSX). After you've confirmed that this is the cause of your problem, set this setting back to "From third parties and advertisers", so that you can reproduce and address the problem with the default settings.
Bare in mind that every time that you want to re-test this issue you will be better off clearing the cache of Safary. Otherwise it could happen that Safari decides that the site serving the API can be trusted and you won't be able to reproduce the issue. So, just to be sure, clear the cache every time that you test this.
I believe that the root of this problem is that Safari wants to make sure that the user has had a direct interaction with the page that it's serving the "3rd party content" before the main page loads that content.
I would need to know more about your project in order to suggest an "optimal" solution. For instance: will the final app be integrated under the same domain as the API? Because if that's the case, you shouldn't have that issue when you go to production. I mean, if the app that you are developing will be hosted under: http://whatever.yourDomain.org and the API is going to be part of that same domain (yourDomain.org), then you shouldn't have that issue at all in production.
On the other hand, if you need to have have the API hosted under a different domain, then you will have to find a way to "trick" Safari. Have a look at this:
Safari 3rd party cookie iframe trick no longer working?
And this:
http://www.allannienhuis.com/archives/2013/11/03/blocked-3rd-party-session-cookies-in-iframes/
I hope that this helps.

stop the web page from loading programmatically

I want to create an extension to firefox using addon builder that
stops users from visiting a malicious website; When I see a URL that is
suspicious, I stop the page from loading and ask the user if he really
wants to visit the site. How could I implement that? I am expecting the functionality programmatically, so that I can make an extension.
if(site.is_malicious)
window.stop();
There is an event called beforescriptexecute supported my mozilla ..... Have a look , I think it will work the job for you. But what you desire can be done something like this:
var r=confirm("Are you sure you want to visit this site ?");
if (r==false) { window.stop(); }
You are creating a FF extension right? Why not use greasemonkey or so? You can execute a script BEFORE the page loads(on greasemonkey). when that script is called, you can potentially stop the pageload and throw an error message.

Categories

Resources