Search code examples
tampermonkeyuserscripts

@grant directive and detecting a user script by a page


My question is two-fold. First, can someone explain what are pros and cons of using @grant none in Tampermonkey? And second, which @grant values I should use to prevent a webpage from detecting a script?


Solution

  • @grant

    If @grant is followed by 'none' the sandbox is disabled and the script will run directly at the page context. In this mode no GM_* function but the GM_info property will be available.

    If a script doesn't need any @grant i.e. the script is plain JavaScript without any GM API, you can use @grant none. Tampermonkey then injects the script into page context (same context as the JavaScript of the webpage).

    Normally userscripts are injected into content context which is separated from the page context.

    If the userscript is injected into page context, then it would be easier for the page to find it. Similarly, if a userscript injected into content context but uses unsafeWindow to interact with the webpage script.

    Webpages can not automatically detect userscripts, but they can check for the result of a script.

    For example ...

    • webpage adds an ad
    • userscript removes the ad
    • webpage check if the ad is still there or not

    Webpage may also look for specific globals that a userscript might add (if the userscript adds globals to the page context).