I love what chrome offers me through its extension API.
But I always find myself lost in the jungle of what API is supported by which chrome version and when did the last chrome.experimental feature make it into the supported extensions.
The Chrome extension page gives me a nice overview what is supported, but without mentioning since what version. The same is true for the experimental API overview. Is that specific API still experimental or is it already supported in canary, for example.
If I try a sample from the chrome Samples website I usually have to change some API calls from chrome.experimental.foo to chrome.foo or find out that it is not supported at all. (What happened to chrome.experimental.alarm?) That usually means to just use the trial and error approach to eliminate all errors, until the sample works.
tldr;
So, I'm wondering is there an overview page which tells me since what version, what API is supported or when it was decided to drop an experimental API. And if there is no such page, what is the recommended way or your personal approach to deal with this situation?
On this page, the process of generating the official documentation (automatically from the Chrome repository) is described. On the same page, you can also read how to retrieve documentation for older branches. Note that the documentation is somehow incomplete: Deprecated APIs are included immediately, although they're still existent (such as onRequest).
What's New in Extensions is a brief list of API changes and updates (excluding most of the experimental APIs). It has to be manually edited, so it's not always up-to-date. For example, the current stable version is 20, but the page's last entry is 19.
If you really need a single page containing all API changes, the following approach can be used:
First, install all Chrome versions. This is not time consuming when done automatically: I've written a script which automates the installation of Chrome, which duplicates a previous profile: see this answer.
Testing for the existence of the feature:
Write a manifest file which includes all permissions (unrecognised permissions are always ignored).
Chrome 18+: Duplicate the extension with manifest version 1 and 2. Some APIs are disabled in manifest version 1 (example).
Testing whether a feature is implemented and behaving as expected is very time-consuming. For this reason, you'd better test for the existence of an API.
A reasonable manner to do this is to recursively loop through the properties of chrome, and log the results (displayed to user / posted to a server).
The process of testing. Use one of the following methods:
Use a single Chrome profile, and start testing at the lowest version.
Use a separate profile for each Chrome version, so that you can test multiple Chrome versions side-by-side.
Post-processing: Interpret the results.
Example code to get information:
/**
* Returns a JSON-serializable object which shows all defined methods
* #param root Root, eg. chrome
* #param results Object, the result will look like {tabs:{get:'function'}}
*/
function getInfo(root, results) {
if (root == null) return results;
var keys = Object.keys(root), i, key;
results = results || {};
for (i=0; i<keys.length; i++) {
key = keys[i];
switch (typeof root[key]) {
case "function":
results[key] = 'function';
break;
case "object":
if (subtree instanceof Array) break; // Exclude arrays
var subtree = results[key] = {};
getInfo(root[key], subtree); // Recursion
break;
default:
/* Do you really want to know about primitives?
* ( Such as chrome.windows.WINDOW_ID_NONE ) */
}
}
return results;
}
/* Example: Get data, so that it can be saved for later use */
var dataToPostForLaterComparision = JSON.stringify(getInfo(chrome, {}));
// ...
Related
The localStorage object in Internet Explorer 11 (Windows 7 build) contains string representations of certain functions instead of native calls as you would expect.
This only breaks with vanilla JavaScript and sites like JSFiddle have no problem with this code but I suspect it's because there are localStorage polyfills in place that correct it.
Take this HTML page code for example:
<!DOCTYPE html>
<script>
localStorage.setItem('test', '12345');
alert(localStorage.getItem('test'));
localStorage.clear();
</script>
This works perfectly well in all my installed browsers except for IE11. An error occurs on the first line 'SCRIPT5002: Function expected'.
Taking a look at what type the setItem function actually is in the IE developer tools console, states that it's a string...?
typeof localStorage.setItem === 'string' // true
Printing out the string for setItem displays the following:
"function() {
var result;
callBeforeHooks(hookSite, this, arguments);
try {
result = func.apply(this, arguments);
} catch (e) {
callExceptHooks(hookSite, this, arguments, e);
throw e;
} finally {
callAfterHooks(hookSite, this, arguments, result);
}
return result;
}"
Oddly enough, not all functions have been replaced with strings, for example, the corresponding getItem function is indeed a function and works as expected.
typeof localStorage.getItem === 'function' // true
Changing the document mode (emulation) to 10 or 9 still doesn't resolve the problem and both result in the same error. Changing the document mode to 8 gives the following error 'Object doesn't support this property or method' which is expected since IE8 doesn't support localStorage.
Is anyone else having the same issue with IE11 on Windows 7 where the localStorage object seems 'broken/corrupt'?
Turns out this is a problem in the base version of IE11 (11.0.9600.16428) for Windows 7 SP1.
After installing a patch to update to 11.0.9600.16476 (update version 11.0.2 - KB2898785) the issue gets resolved. Links to other versions of Windows (32-bit etc.) can be found at the bottom of the patch download page.
It's not just IE11's fault.
Probably WEINRE is injected into the page. It hooks into several system functions to provide Developer Tools functionality, but IE11 interprets assignments to the localStorage and sessionStorage properties wrong, and converts the hook functions into strings, as if they were the data that is going to be stored.
There's a comment in the apache/cordova-weinre repo which says:
#In IE we should not override standard storage functions because IE does it incorrectly - all values that set as
# storage properties (e.g. localStorage.setItem = function()[...]) are cast to String.
# That leads to "Function expected" exception when any of overridden function is called.
object[property] = hookedFunction unless navigator.userAgent.match(/MSIE/i) and (object is localStorage or object is sessionStorage)
Looks like it's either an old version of WEINRE being used, or this change hasn't been officially released (it's been there since 2013).
My localStorage returned undefined and I couldn't figure out why - until I realized that it was because I was running the HTML-page (with the localStorage script) directly from my computer (file:///C:/Users/...). When I accessed the page from a server/localhost instead it localStorage was indeed defined and worked.
In addition to the already excellent answers here, I'd like to add another observation. In my case, the NTFS permissions on the Windows %LOCALAPPDATA% directory structure were somehow broken.
To diagnose this issue. I created a new Windows account (profile), which worked fine with the localStorage,so then I painstakingly traversed the respective %LOCALAPPDATA%\Microsoft\Internet Explorer trees looking for discrepancies.
I found this gem:
C:\Users\User\AppData\Local\Microsoft>icacls "Internet Explorer"
Internet Explorer Everyone:(F)
I have NO idea how the permissions were set wide open!
Worse, all of the subdirectories has all permissions off. No wonder the DOMStore was inaccessible!
The working permissions from the other account were:
NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
my-pc\test:(OI)(CI)(F)
Which matched the permissions of the parent directory.
So, in a fit of laziness, I fixed the problem by having all directories "Internet Explorer" and under inherit the permissions. The RIGHT thing to do would be to manually apply each permission and not rely on the inherit function. But one thing to check is the NTFS permissions of %LOCALAPPDATA%\Microsoft\Internet Explorer if you experience this issue. If DOMStore has broken permissions, all attempts to access localStorage will be met with Access Denied.
I'm trying to detect if an extension is installed on a user's browser.
I tried this:
var detect = function(base, if_installed, if_not_installed) {
var s = document.createElement('script');
s.onerror = if_not_installed;
s.onload = if_installed;
document.body.appendChild(s);
s.src = base + '/manifest.json';
}
detect('chrome-extension://' + addon_id_youre_after, function() {alert('boom!');});
If the browser has the extension installed I will get an error like:
Resources must be listed in the web_accessible_resources manifest key
in order to be loaded by pages outside the extension
GET chrome-extension://invalid net::ERR_FAILED
If not, I will get a different error.
GET chrome-extension://addon_id_youre_after/manifest.json net::ERR_FAILED
Here is an image of the errors I am getting:
I tried to catch the errors (fiddle)
try {
var s = document.createElement('script');
//s.onerror = window.setTimeout(function() {throw new Error()}, 0);
s.onload = function(){alert("installed")};
document.body.appendChild(s);
s.src = 'chrome-extension://gcbommkclmclpchllfjekcdonpmejbdp/manifest.json';
} catch (e) {
debugger;
alert(e);
}
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj);
}
So far I am not able to catch the errors..
Any help will be appreciated
The first error is informative from Chrome, injected directly into the console and not catchable by you (as you noticed).
The GET errors are from the network stack. Chrome denies load in either case and simulates a network error - which you can catch with onerror handler on the element itself, but not in the window.onerror hander. Quote, emphasis mine:
When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element, that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a single capturing window.addEventListener.
Here's an example that will, at least, detect the network error. Note that, again, you can't catch them, as in prevent it from showing in the console. It was a source of an embarrasing problem when Google Cast extension (that was exposing a resource) was using it as a detection method.
s.onload = function(){alert("installed")};
s.error = function(){alert("I still don't know")};
Notice that you can't distinguish between the two. Internally, Chrome redirects one of the requests to chrome-extension://invalid, but such redirects are transparent to your code: be it loading a resource (like you do) or using XHR. Even the new Fetch API, that's supposed to give more control over redirects, can't help since it's not a HTTP redirect. All it gets is an uninformative network error.
As such, you can't detect whether the extension is not installed or installed, but does not expose the resource.
Please understand that this is intentional. The method you refer to used to work - you could fetch any resource known by name. But it was a method of fingerprint browsers - something that Google is explicitly calling "malicious" and wants to prevent.
As a result, web_accessible_resources model was introduced in Chrome 18 (all the way back in Aug 2012) to shield extensions from sniffing - requiring to explicitly declare resources that are exposed. Quote, emphasis mine:
Prior to manifest version 2 all resources within an extension could be accessed from any page on the web. This allowed a malicious website to fingerprint the extensions that a user has installed or exploit vulnerabilities (for example XSS bugs) within installed extensions. Limiting availability to only resources which are explicitly intended to be web accessible serves to both minimize the available attack surface and protect the privacy of users.
With Google actively fighting fingerprinting, only cooperating extensions can be reliably detected. There may be extension-specific hacks - such as specific DOM changes, request interceptions or exposed resources you can fetch - but there is no general method, and extension may change their "visible signature" at any time. I explained it in this question: Javascript check if user has a third party chrome extension installed, but I hope you can see the reason for this better.
To sum this up, if you indeed were to find a general method that exposed arbitrary extensions to fingerprinting, this would be considered malicious and a privacy bug in Chrome.
Have your Chrome extension look for a specific DIV or other element on your page, with a very specific ID.
For example:-
<div id="ExtensionCheck_JamesEggersAwesomeExtension"></div>
I'm tring to download an offline map pack. Trying to reverse engineer the example project from the skobbler support website, however when trying to start a download the download manager crashes.
What my usecase is: show a list of available countries (within the EUR continent) and make the user select a single one, and that will be downloaded at that time. So far I have gotten a list where those options are available. Upon selecting an item (and starting the download) it crashes.
For the sake of the question I commented out some things.
Relevant code:
// Get the information about where to obtain the files from
SKPackageURLInfo urlInfo = SKPackageManager.getInstance().getURLInfoForPackageWithCode(pack.packageCode);
// Steps: SKM, ZIP, TXG
List<SKToolsFileDownloadStep> downloadSteps = new ArrayList<>();
downloadSteps.add(new SKToolsFileDownloadStep(urlInfo.getMapURL(), pack.file, pack.skmsize)); // SKM
//downloadSteps.add(); // TODO ZIP
//downloadSteps.add()); // TODO TXG
List<SKToolsDownloadItem> downloadItems = new ArrayList<>(1);
downloadItems.add(new SKToolsDownloadItem(pack.packageCode, downloadSteps, SKToolsDownloadItem.QUEUED, true, true));
mDownloadManager.startDownload(downloadItems); // This is where the crash is
I am noticing a running download, since the onDownloadProgress() is getting triggered (callback from the manager). However the SKToolsDownloadItem that it takes as a parameter says that the stepIndex starts at 0. I don't know how this can be, since I manually put that at (byte) 0, just like the example does.
Also, the logs throw a warning on SingleClientConnManager, telling me:
Invalid use of SingleClientConnManager: connection still allocated.
This is code that gets called from within the manager somewhere. I am thinking there is some vital setup steps missing from the documentation and the example project.
I have a google chrome extension that shares some code between it's content script and background process / popup. If it some easy and straightforward way for this code to check if it's executed as content script or not? (message passing behavior differs).
I can include additional "marker" javascript in manifest or call some chrome fnction unavailable from content script and check for exceptions - but these methods looks awkward to be. Maybe it's some easy and clean way to make this check?
To check whether or not your script is running as a content script, check if it is not being executed on a chrome-extension scheme.
if (location.protocol == 'chrome-extension:') {
// Running in the extension's process
// Background-specific code (actually, it could also be a popup/options page)
} else {
// Content script code
}
If you further want to know if you're running in a background page, use chrome.extension.getBackgroundPage()=== window. If it's true, the code is running in the background. If not, you're running in the context of a popup / options page / ...
(If you want to detect if the code is running in the context of an extension, ie not in the context of a regular web page, check if chrome.extension exists.)
Explanation of revised answer
Previously, my answer suggested to check whether background-specific APIs such as chrome.tabs were defined. Since Chrome 27 / Opera 15, this approach comes with an unwanted side-effect: Even if you don't use the method, the following error is logged to the console (at most once per page load per API):
chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.
This doesn't affect your code (!!chrome.tabs will still be false), but users (developers) may get annoyed, and uninstall your extension.
The function chrome.extension.getBackgroundPage is not defined at all in content scripts, so alone it can be used to detect whether the code is running in a content script:
if (chrome.extension.getBackgroundPage) {
// background page, options page, popup, etc
} else {
// content script
}
There are more robust ways to detect each context separately in a module I wrote
function runningScript() {
// This function will return the currently running script of a Chrome extension
if (location.protocol == 'chrome-extension:') {
if (location.pathname == "/_generated_background_page.html")
return "background";
else
return location.pathname; // Will return "/popup.html" if that is the name of your popup
}
else
return "content";
}
I've been searching for examples and reference and have come up with nothing. I found a note in offscreenTab source code mentioning it cannot be instantiated from a background page (it doesn't have a tab for the offscreenTab to relate to). Elsewhere I found mention that popup also has no tie to a tab.
How do you successfully create an offscreenTab in a Chrome extension?
According to the documentation, offscreenTabs.create won't function in a background page. Although not explicitly mentioned, the API cannot be used in a Content script either. Through a simple test, it seems that the popup has the same limitation as a background page.
The only leftover option is a tab which runs in the context of a Chrome extension. The easiest way to do that is by using the following code in the background/popup:
chrome.tabs.create({url: chrome.extension.getURL('ost.htm'), active:false});
// active:false, so that the window do not jump to the front
ost.htm is a helper page, which creates the tab:
chrome.experimental.offscreenTabs.create({url: '...'}, function(offscreenTab) {
// Do something with offscreenTab.id !
});
To change the URL, use chrome.experimental.offscreenTabs.update.
offscreenTab.id is a tabId, which ought to be used with the chrome.tabs API. However, at least in Chrome 20.0.1130.1, this is not the case. All methods of the tabs API do not recognise the returned tabID.
A work-around is to inject a content script using a manifest file, eg:
{"content_scripts": {"js":["contentscript.js"], "matches":["<all_urls>"]}}
// contentscript.js:
chrome.extension.sendMessage({ .. any request .. }, function(response) {
// Do something with response.
});
Appendum to the background page:
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
// Instead of checking for index == -1, you can also see if the ID matches
// the ID of a previously created offscreenTab
if (sender.tab && sender.tab.index === -1) {
// index is negative if the tab is invisible
// ... do something (logic) ...
sendResponse( /* .. some response .. */ );
}
});
With content scripts, you've got full access to a page's DOM. But not to the global object. You'll have to inject scripts (see this answer) if you want to run code in the context of the page.
Another API which might be useful is the chrome.webRequest API. It can be used to modify headers/abort/redirect requests. Note: It cannot be used to read or modify the response.
Currently, the offscreenTabs API is experimental. To play with it, you have to enable the experimental APIs via chrome://flags, and add "permissions":["experimental"] to your manifest file. Once it's not experimental any more, use "permissions":["offscreenTabs"].