How to detect if a userscript is installed from the Chrome Store?

浪尽此生 提交于 2019-12-21 22:56:59

问题


I want to notify the user when an update for my Greasemonkey/UserScript is available. However when the user has installed the script from the Chrome Web Store, I don't want to bother because it has auto-update functionality.

I first thought about using $.browser==chrome but it is also possible that a Chrome user has installed it using Tampermonkey. (Furthermore if the site would update jQuery, $.browser would stop working)

So, is it possible to detect that it is a UserScript installed through the Chrome Web Store?


回答1:


Probably best to just let the user know that an update is available, and not worry about the platform. Also it's not clear how cross-browser this script is. You may have to resort to browser sniffing (not usually recommended) to be absolutely sure.


You can use the scriptHandler property of the GM_info object, if you are only concerned about Chrome and/or Firefox:

// ==UserScript==
// @name     _Rough script handler detector
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// ==/UserScript==
var scriptEngine;

if (typeof GM_info === "undefined") {
    scriptEngine = "plain Chrome (Or Opera, or scriptish, or Safari, or rarer)";
    // See https://stackoverflow.com/a/2401861/331508 for optional browser sniffing code.
}
else {
    scriptEngine = GM_info.scriptHandler  ||  "Greasemonkey";
}
console.log ('This userscript is running on ' + scriptEngine + '.');

Which yields:
Tampermonkey:

This userscript is running on Tampermonkey.

Greasemonkey (Strictly Firefox):

This userscript is running on Greasemonkey.

Chrome from the web store, or other:

This userscript is running on plain Chrome (Or Opera, or scriptish, or Safari, or rarer).

Because only the big engines (Greasemonkey and Tampermonkey) currently support GM_info, if your userscript is especially cross-browser, you will need to do browser sniffing to differentiate in rarer cases.
See this answer for browser-sniffing code that doesn't require jQuery.


Note: A @grant directive is not needed to use GM_info.



来源:https://stackoverflow.com/questions/27487828/how-to-detect-if-a-userscript-is-installed-from-the-chrome-store

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!