Reliably getting favicons in Chrome extensions, chrome://favicon? - permissions

I'm using the chrome://favicon/ in my Google Chrome extension to get the favicon for RSS feeds. What I do is get the base path of linked page, and append it to chrome://favicon/http://<domainpath>.
It's working really unreliably. A lot of the time it's reporting the standard "no-favicon"-icon, even when the page really has a favicon. There is almost 0 documentation regarding the chrome://favicon mechanism, so it's difficult to understand how it actually works. Is it just a cache of links that have been visited? Is it possible to detect if there was an icon or not?
From some simple testing it's just a cache of favicons for pages you have visited. So if I subscribe to dribbble.com's RSS feed, it won't show a favicon in my extension. Then if I visit chrome://favicon/http://dribbble.com/ it won't return right icon. Then I open dribbble.com in another tab, it shows its icon in the tab, then when I reload the chrome://favicon/http://dribbble.com/-tab, it will return the correct favicon. Then I open my extensions popup and it still shows the standard icon. But if I then restart Chrome it will get the correct icon everywhere.
Now that's just from some basic research, and doesn't get me any closer to a solution. So my question is: Is the chrome://favicon/ a correct use-case for what I'm doing. Is there any documentation for it? And what is this its intended behavior?

I've seen this problem as well and it's really obnoxious.
From what I can tell, Chrome populates the chrome://favicon/ cache after you visit a URL (omitting the #hash part of the URL if any). It appears to usually populate this cache sometime after a page is completely loaded. If you try to access chrome://favicon/http://yoururl.com before the associated page is completely loaded you will often get back the default 'globe icon'. Subsequently refreshing the page you're displaying the icon(s) on will then fix them.
So, if you can, possibly just refreshing the page you're displaying the icons on just prior to displaying it to the user may serve as a fix.
In my use case, I am actually opening tabs which I want to obtain the favicons from. So far the most reliable approach I have found to obtain them looks roughly like this:
chrome.webNavigation.onCompleted.addListener(onCompleted);
function onCompleted(details)
{
if (details.frameId > 0)
{
// we don't care about activity occurring within a subframe of a tab
return;
}
chrome.tabs.get(details.tabId, function(tab) {
var url = tab.url ? tab.url.replace(/#.*$/, '') : ''; // drop #hash
var favicon;
var delay;
if (tab.favIconUrl && tab.favIconUrl != ''
&& tab.favIconUrl.indexOf('chrome://favicon/') == -1) {
// favicon appears to be a normal url
favicon = tab.favIconUrl;
delay = 0;
}
else {
// couldn't obtain favicon as a normal url, try chrome://favicon/url
favicon = 'chrome://favicon/' + url;
delay = 100; // larger values will probably be more reliable
}
setTimeout(function() {
/// set favicon wherever it needs to be set here
console.log('delay', delay, 'tabId', tab.id, 'favicon', favicon);
}, delay);
});
}
This approach returns the correct favicon about 95% of the time for new URLs, using delay=100. Increasing the delay if you can accept it will increase the reliability (I'm using 1500ms for my use case and it misses <1% of the time on new URLs; this reliability worsens when many tabs are being opened simultaneously). Obviously this is a pretty imprecise way of making it work but it is the best method I've figured out so far.
Another possible approach is to instead pull favicons from http://www.google.com/s2/favicons?domain=somedomain.com. I don't like this approach very much as it requires accessing the external network, relies on a service that has no guarantee of being up, and is itself somewhat unreliable; I have seen it inconsistently return the "globe" icon for a www.domain.com URL yet return the proper icon for just domain.com.
Hope this helps in some way.

As of Oct 2020, it appears chrome extensions using manifest version 3 are no longer able to access chrome://favicon/* urls. I haven't found the 'dedicated API' the message refers to.
Manifest v3 and higher extensions will not have access to the
chrome://favicon host; instead, we'll provide a dedicated API
permission and different URL. This results in being able to
tighten our permissions around the chrome:-scheme.

In order to use chrome://favicon/some-site in extension. manifest.json need to be updated:
"permissions": ["chrome://favicon/"],
"content_security_policy": "img-src chrome://favicon;"
Test on Version 63.0.3239.132 (Official Build) (64-bit)

chrome://favicon url is deprecated in favor of new favicon API with manifest v3.
// manifest.json
{
"permissions": ["favicon"]
}
// utils.js
function getFaviconUrl(url) {
return `chrome-extension://${chrome.runtime.id}/_favicon/?pageUrl=${encodeURIComponent(url)}&size=32`;
}
Source: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/qS1rVpQVl8o/m/qmg1M13wBAAJ

I inspected the website-icon in Chrome history page and found this simpler method.
You can get the favicon url by --
favIconURL = "chrome://favicon/size/16#1x/" + tab.url;
Don't forget to add "permissions" and "content_security_policy" to Chrome. (https://stackoverflow.com/a/48304708/9586876)

In the latest version of Chrome, Version 78.0.3904.87 (Official Build) (64-bit)) when tested, adding just img-src chrome://favicon; as content_security_policy will still show 2 warnings:
'content_security_policy': CSP directive 'script-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.
And:
'content_security_policy': CSP directive 'object-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.
To get rid of them use:
"permissions": ["chrome://favicon/"],
"content_security_policy": "script-src 'self'; object-src 'self'; img-src chrome://favicon;"
Now you can use chrome://favicon/http://example.com without getting any errors or warnings.

Related

How to save url and use out of chrome api in Vue.js for chrome extension?

I am currently facing a weird issue with developing a simple chrome extension.
Basically, I want to build an extension that saves the currently focused URL. However, seems like URL is not saved in variables that I defined.
I have tried to use an array to store it, and also a variable.
consoleClick() {
var urlss = []
var getTab = function(tab){
urlss.push(tab)
alert(tab)
};
chrome.tabs.query({'active':true}, function(tabs){
getTab(tabs[0].url)
});
console.log(urlss)
this.$store.commit('addUrl',urlss[0])
console.log(this.$store.state.urls[0])
}
Here, once button is clicked, with "chrome.tabs.query()" I was able to get currently focused url. and I saved it to "urlss", and checked it with console.log(urlss).
I could see the url in console log, however, when I tried to access to url with urlss[0], it says urlss[0] is "undefined" even though I can see that
[]
0: "https://stackoverflow.com/posts/57089954/edit"
length: 1
__proto__: Array(0)
in log. This leads to push "undefined" to my vuex storage.
I also tried to push it to vuex storage right away in chrome.tabs.query(), however it gives me that $store is not defined.
I know that my explanation is pretty messy but I need help from the community! Thanks in advance

How to detect private browsing in iOS 11 Mobile Safari or MacOS High Sierra Safari?

On the new iOS 11 Safari and MacOS High Sierra Safari, that trick of seeing if window.localStorage.setItem('test', 1); (see https://stackoverflow.com/a/17741714/1330341) throws an error no longer works, because it no longer throws an error, and it also properly sets the localStorage item. Has anyone figured out any other way to check for private browsing mode in the new versions of Safari?
Haven't actually tried it, but from reading Apple's document:
https://support.apple.com/kb/ph21413?locale=en_US
It lists various characteristics of private mode browsing (~snip):
When you use a Private Browsing window:
Each tab in the window is isolated from the others, so websites you
view in one tab can’t track your browsing in other tabs.
Safari doesn’t remember the webpages you visit or your AutoFill
information.
Safari doesn’t store your open webpages in iCloud, so they aren’t
shown when you view all your open tabs from other devices.
Your recent searches aren’t included in the results list when you use
the Smart Search field.
Items you download aren’t included in the downloads list. (The items
do remain on your computer.)
If you use Handoff, Private Browsing windows are not passed to your
iOS devices or other Mac computers.
Safari doesn’t remember changes to your cookies or other website
data. Safari also asks websites and others who provide those sites
with content (including advertisers) not to keep track of your
browsing, although it is up to the websites to honor this request.
Plug-ins that support Private Browsing stop storing cookies and other
tracking information.
From the above, in particular I found interesting that Safari specifically asks websites to "not track" the browsing. This could potentially be a mechanism to look for, to determine if using private browsing.
See this answer for an example:
Implementing Do not track in asp.net mvc
Again, haven't tested and unsure if it will work, but if not the list provides other potential options. HTH.
I find a solution here:
https://gist.github.com/cou929/7973956#gistcomment-2272103
var isPrivate = false;
try {
window.openDatabase(null, null, null, null);
} catch (_) {
isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t') + ' in private browsing mode');
Hope it helps :)
Quote from apple's website. https://support.apple.com/kb/ph21413?locale=en_US
Websites can’t modify information stored on your device, so services
normally available at such sites may work differently until you turn
off Private Browsing
So, store a test variable, change its value, then read the test variable.
If you get an exception, are unable to find the variable, the value didn't change or you get a null/undefined value back, they are most likely in private mode.
Alternatively, in private browsing, you have no stored search history accessible. So, redirect to a new page in your site on startup and then test if you have any previous history. If not and the fact that you are getting a Do Not Track most likely means your in private mode on safari.
Please note that I have not tested this. This is based off the information provided by Apple in the above link.
Thing that I realized is Safari throws a "Quota Exceeded" error in the Private mode. So here is what I did!
isPrivateMode: function () {
if (localStorage.length === 0) {
try {
localStorage.setItem('isLocalStorageAvaialble', 'That is being tested!');
localStorage.removeItem('isLocalStorageAvaialble');
return false;
} catch (e) {
return true;
}
}
}
Checking the length of localStorage is important for the fact that, if you are trying this method on a browser that supports localStorage, but is full, you still will get the "Quota Exceeded" error.
In private mode, the length of localStorage is always 0.
Hope this helps!

Safari extension options pages with access to background page

I'm developing a cross-platform browser extension, and have based all my code on the Chrome-way of doing this. I have counted on that the background page will be accessible from the options page, which in Safari extensions turns out to be not possible (since there is no such thing as an options-page). You can only access safari.extension.globalPage.contentWindow from within the extension popup, and the background page itself.
Now, I have an options page, which is an html-page within the extension bundle, and so far I haven't found a way for Safari to give it extension "rights". The closest I have come is adding a content script that's only added on the options page. This seems a bit silly, since the html page itself is in the extension bundle?!
Others have suggested using asynchronous ping-pong style message event handlers, and even the canLoad-mechanism (which is "only" able to run in a beforeload-event). I have been able to hack the canLoad-mechanism for synchronous messaging by forging the BeforeLoadEvent:
// Content script (run from anywhere)
var result = safari.self.tab.canLoad(new BeforeLoadEvent, "data")
-> "return value"
// Background page
safari.application.addEventListener('message', function(e) {
if ( e.name === "canLoad" )
e.message = "return value";
}, true);
It's a hack, but it works. However, I am crippled by the message transport serialization, since I need to be able access methods and data on my objects from the background page. Is there anyway around this?
Possible ways that might work but I don't know if possible:
Access options-page window-object from backgrounds page. Is that possible?
Message passing, need to bypass message serialization
Any shared/global object that I can attach objects to and fetch from the options page?
Make Safari run the options.html page from outside the content-script sandbox? It works in Chrome since they are both within the extension-bundle. It's quite annoying that safari doesn't do this too.
Run the options-page from within the popup. This is promising, but it crashes safari (which is very promising!). However, from the looks of it it's just something to do with a CSS animation in my options.html page. The biggest issue is that it has to be able to open an OAuth2 popup, but thanks to being able to programmatically open the popover, it might be a non-issue. However, this option is the most realistic, but I would rather have it open in a new tab.
Any suggestions and hackish workarounds would really help.

YII compress your application output using gzip

what is the benefit of below code that is two events.
what its actually doing ??
require_once($yii);
$app = Yii::createWebApplication($config);
Yii::app()->onBeginRequest = function($event)
{
return ob_start("ob_gzhandler");
};
Yii::app()->onEndRequest = function($event)
{
return ob_end_flush();
};
$app->run();
please explain the function of this code in my application.what it does ?? and how can it help me ??
The above code buffers the content and gzips it according to browser, rather than sending it straight away.
Yii::app()->onBeginRequest = function($event)
{
return ob_start("ob_gzhandler");
};
The above means that when the requests starts, it will buffer the content, and using the callback will set the content as gzip,deflate or none, depending on browser.
Yii::app()->onEndRequest = function($event)
{
return ob_end_flush();
};
The above code simply means that at the end of the request, it will output the buffer contents.
It buffers the content, and just before sending it the browser, asks if the browser can accept zipped content. If it can, it will zip the HTML before supplying. Otherwise, it will supply it unzipped.
Zipped content reduces the size of the HTML the browser needs to download, which can increase performance. How much performance gain your users will see depends on the size of the HTML - bigger pages will see more benefit, while tiny pages may actually take longer to render, because the browser has to unzip the content first. Use Firebug or Chrome Developer Toolbars to see whether it's worth it.
Also, check the impact on the server side. Again, the downside of increased server load can outweigh the increased client-side page render speed. Hence, it works best with lots of caching.
This is normally something you do when you are optimising the site, looking for performance gains.
if you want add gzhanlder straight to main config file you Can Set Following lines in main.php
'onBeginRequest'=>create_function('$event', 'return ob_start("ob_gzhandler");'),
'onEndRequest'=>create_function('$event', 'return ob_end_flush();'),
this Two lines Add GzipHandler

Secured and unsecured items message in IE

I'm getting "This page contains bothe Secure and Non secure items"message in IE. When I commented the following piece of code from dojo.js.uncompressed.js file, the message is gone.
if(dojo.isIE){
if(!dojo.config.afterOnLoad){
document.write('<scr'+'ipt defer src="//:" '
+ 'onreadystatechange="if(this.readyState==\'complete\'){' + dojo._scopeName + '._loadInit();}">'
+ '</scr'+'ipt>'
);
}
Is that an issue with the dojo? I would like to move the commented code to another custom file so that the dojo framework is not affected. Can you suggest a better way of implementing it.
Thanks.
You would get that error if you're using frames or have external files where some of the files have https URLs while some have http URLs. Assuming, your main page loads up through https, you could try changing:
src="//:"
to:
src="https//:"
the //: is most likely the problem, as I ran into a similar issue with a chunk of javascript code... In internet explorer, the locaiton //: is not secure, so when your page (presumably on an https:// url) loads, IE notes that you've got your main code loading from a secure location, and another script being loaded in from an unsecure location.
The workaround that I came to was to create an empty file in my web root named "blank.html" (though "blank.js" would probably work better in your case) and replace the //: link with "/blank.html". This results in another hit to your webserver, but browser caching will probably make that impact minimal.