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

巧了我就是萌 提交于 2019-12-04 15:01:48
Brock Adams

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.

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