First, it is important to clarify that Tampermonkey scripts are typically managed and executed through the Tampermonkey extension, and the Tampermonkey extension itself does not directly provide an interface to determine if a script was installed from the Chrome Web Store. However, we can infer or detect this through some indirect methods.
Technical Approach
1. Checking the script's metadata: Each Tampermonkey script includes a metadata section, which typically contains information such as the script's source and version number. Although this section can be customized by the script author, if we require that scripts downloaded from the Chrome Web Store must include specific markers or links, we can determine if the script was installed from the Chrome Web Store by parsing this metadata.
javascript// ==UserScript== // @name Example Script // @namespace http://tampermonkey.net/ // @version 0.1 // @description Try it // @author Your Name // @match http://*/* // @grant none // @fromStore true // ==/UserScript== (function() { 'use strict'; if (GM_info.script.fromStore === 'true') { console.log('This script was installed from the Chrome Web Store'); } else { console.log('This script was not installed from the Chrome Web Store'); } })();
2. Checking extension source using browser APIs:
This method is more complex and requires the script to access browser extension APIs, such as the chrome.management API. Through this API, we can retrieve detailed information about all installed extensions, including their source. However, this typically requires users to grant additional permissions, and Tampermonkey scripts themselves restrict the use of some APIs.
3. Server-side verification: If you have control over the server, you can require all scripts installed from the Chrome Web Store to undergo server-side verification during installation, with the server recording the IDs of all verified scripts. Subsequently, the script can send requests to the server during execution to check if its ID is in the verification list.
Conclusion
Due to the high openness and customizability of Tampermonkey scripts, determining solely from the script itself whether it was installed from the Chrome Web Store can be challenging and uncertain. Typically, combining metadata markers with server-side verification is a relatively feasible approach. It is important to note that these methods can potentially be bypassed, so security and accuracy cannot be fully guaranteed. In practical applications, the most suitable method can be chosen based on specific circumstances.