Is it possible to determine if Chrome is in incognito mode via a user-script? - google-chrome-extension

I asked this question before but didn't make it clear that I meant in user script, not in JavaScript from a webpage.So I'll be more clear now.
Is it possible to determine if Google Chrome is in incognito mode via a user-script (basically a script run as an extension in the browser, not a script being run on a webpage)?

To detect whether a window is in
incognito mode, check the incognito
property of the relevant Tab or
Window object. For example:
var bgPage = chrome.extension.getBackgroundPage();
function saveTabData(tab, data) {
if (tab.incognito) {
bgPage[tab.url] = data; // Persist data ONLY in memory
} else {
localStorage[tab.url] = data; // OK to store data
}
http://code.google.com/chrome/extensions/overview.html

If you are developing an Extension then you can use the tabs API to determine if a window/tab incognito.
More information can be found on code.google.com.
If you are just working with a webpage or a userscript, it is not easy, and it is designed to be that way. However, I have noticed that all attempts to open a database (window.database) fail when in incongnito, this is because when in incognito no trace of data is allowed to be left on the users machine.
I haven't tested it but I suspect all calls to localStorage fail too.

Nowadays it's quite easy to do this from a content script. Just use
if(chrome.extension.inIncognitoContext) {
//you're incognito
} else {
//you're not
}

Related

Detect when developer mode is enabled

Is there a way to detect when Developer mode is enabled?
The reason I'd like to detect this, is because my extension produces a lot of debug information in the console. And to avoid unnecessary performance lose, I'd like to disable output if dev mode is disabled.
At the moment, I'm using this little hack, which only output data if extension is unpacked:
chrome.management.getSelf().then(data=>debug.show=data.installType=="development");
const debug = new Proxy({show:false,void:()=>{}},
{
get(target, prop)
{
return target.show ? console[prop].bind(console) : target.void;
}
});
But I'd like to be able to test it in packed state as well.

How can I know if browser is Chrome vs Firefox from web extension popup JavaScript?

I am using the chrome namespace for both Chrome and Firefox, but would like to know which browser is running the web extension.
Links to extension resources have different schemes in Chrome and Firefox.
const isFirefox = chrome.runtime.getURL('').startsWith('moz-extension://');
const isChrome = chrome.runtime.getURL('').startsWith('chrome-extension://');
Check chrome.app which is absent in Firefox:
const isFirefox = !chrome.app;
Check for browser which is absent in Chrome:
const isFirefox = window.browser && browser.runtime;
(the additional check is to avoid false positives on pages that have an element with id="browser" that creates a named property on window object for this element)
Use the asynchronous browser.runtime.getBrowserInfo.
P.S. navigator.userAgent may be changed during debugging in devtools when switching to device mode or via about:config option in Firefox so it's an unreliable source.
This is what I do in my own extensions to check for Firefox (FF) vs Chrome:
const FF = typeof browser !== 'undefined';
Update: (1)
Here is an explanation .....
I am using the chrome namespace for both Chrome and Firefox, but would
like to know which browser is running the web extension.
AFA I understand, the question relates to extension code and not content code. I use above code in background script in "firefox-webextensions" or "google-chrome-extension" background script.
From then on then code would be:
if (FF) {...}
else { .... }
Once established, content script has no bearing on it.
In case of a developer who somehow decides to use id="browser" then a further step could be added which returns a boolean true|false e.g.
const FF = typeof browser !== 'undefined' && !!browser.runtime;
Worth nothing that the following returns an object or undefined and not a boolean
const isFirefox = window.browser && browser.runtime;
While it works fine in if() conditionals, it wont work in other situations where a boolean would be required (e.g. switch)
(1) Note: Marking down answers, discourages people from spending time and effort in answering questions in future.

how to connect extension with content script in Firefox for android? [duplicate]

I just noticed that the tabs API is only available for the desktop not for Android. In the past I have used this code to send messages to my content scripts:
sendMsgToTabs(msg) {
return browser.tabs.query({}).then(tabs => {
let msgPromises = []
for (let tab of tabs) {
let msgPromise = browser.tabs.sendMessage(tab.id, msg)
msgPromises.push(msgPromise)
}
return Promise.all(msgPromises)
})
}
But how am I supposed to do that when the tabs API is not available?
I mean the only thing I can think of is to constantly send empty messages from the content scripts to the background script and whenever the background script has new information then it can send a direct response to one of these messages. But that sounds horribly inefficient. There must be a better way, right?
As of Firefox 54, use .tabs.sendMessage()
As of Firefox 54, the tabs API is supported on Firefox for Android.
Alternative for versions of Firefox prior to Firefox 54.
The storage API is stated as supported in Firefox for Android. Thus, while I have not tested it, a method you could use to send data to content script would be to save a value using chrome.storage.local.set(). By listening to the chrome.storage.onChanged event in your content script(s), you can then be notified of that data being stored/changed. This will provide an event driven way to send a message (i.e. stored data) to the content script.
In order to differentiate between receiving the data in different tabs, you will need to establish a protocol for what the data you save means. This could be as simple as just a particular saved key/value meaning that all content scripts should send a message to the background script to get more information, or more complex where you send/store something like:
{
contentScriptMessage: {
tab: 14,
frame: 1234,
message: 'Some data'
}
}
In each content script's chrome.storage.onChanged listener, it can then ignore any changes that are not to the tab/frame in which it is running.
This methodology will require fleshing out as you try to implement it. Hopefully, at least part of the chrome.tabs API will be implemented for Android in the near future.

Can js code in chrome extension detect that it's executed as content script?

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";
}

How to use the experimental offscreenTab API?

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"].

Resources