Calling a function before the document loads up in JS - javascript

My friend asks me to do this.
He needs to prevent his children from going to certain websites.
He has tamper monkey installed with chrome. I have to make a script in tamper-monkey so that when it reaches the website it will change the web content.
The source code is:
// ==UserScript==
// #name My Fancy New Userscript
// #namespace http://use.i.E.your.homepage/
// #version 0.1
// #description enter something useful
// #match http://www.harmful-website.com/*
// #copyright 2012+, You
// ==/UserScript==
document.write("<b>You are not allowed to visit this site</b>");
This script works only after the web-site is loaded full. But his children stop the loading of website in the middle and they are able to view a part of it.
Even document.onload=function(){document.write("...");} works after load. Are there any way to make the script run before the document is loaded i.e. Immediately after the web address is typed on the address bar or hyperlink is clicked.

Your code will work, you just need to set #run-at document-startDoc, like so:
// ==UserScript==
// #name site blocker
// #match http://www.harmful-website.com/*
// #run-at document-start
// ==/UserScript==
document.write ("<b>You are not allowed to visit this site</b>");
Important:
This will work, for now, on Chrome and with Tampermonkey, but it does not work on other browsers. For example, on Firefox, the document.write call will throw the error:
Error: The operation is insecure.
(But the page will still be completely blank.)
Although a userscript like this will work (mostly); it is a klugey, brittle, low performance approach and is easily defeated. Here are just a few ways that are better, faster, easier, and harder for savvy kids to kibosh:
Use your home router's siteblock and/or parental controls. Almost every router and/or modem has this feature, these days.
Install one of the many extensions that do this kind of blocking.
Block the site with an Adblock rule.
Block the site with the machine's hosts file.
Use a proxy server.
Search on Super User for more options.

Just call the function right after you define it. Like in the header or somehwere.
However, you need to consider if the function has actually everything it requires, like HTML elements on the page if it access any of them, as those won't necessarily be loaded when calling your function.

HTML file is parsed row by row. So if your write your < script > just after < html > tag it will be executed before anything else.

Related

Develop Tampermonkey scripts in a real IDE with automatic deployment to OpenUserJs repo

I recently started development on a Tampermonkey script, which is hosted on OpenUserJs. It seems that I'm going to invest a bit more time in the future on this script by keep it up to date and extend his features when time is there. The first lines I wrote on the Tampermonkey editor which is integrated in chrome (edit button of a script).
But I don't like it, the most thing I'm missing is some kind of autocomplete/intellisense. Visual Studio is much better here, so I switched to VS. The problem: After any changes, I have to copy the hole code and paste it in the Tampermonkey editor (Google Chrome). Thats annoying and not very flexible, since I can't really split my code in multiple js files when the script grows.
So is there a way to automate this? My imagination would be: I save the js file in VS (ctrl + s), then the script is loaded in my local development instance of google chrome for testing purpose.
Extension:
I want to publish alpha/beta releases as hosted version on OpenUserJs. So I can test the release easily on different systems. And I also have at least one system, where I do the real update process over the OpenUserJs repo like my end users will do. I think this is important, I already saw some differences according to my manual workflow (c&p in the OpenUserJs editor).
My preferable soultion would be some kind of branches like I know from git. So that I install the script from OpenUserJs like my users do with the production one, but I can choose somewhere to get e.g. the branch development instead of master. OpenUserJs seems to support github as source base, but no kind of branches. I can't imagine, that there is no solution for such issues, which at least every developer with bigger scripts should have...
I found my way to it, so it's not official or anything. And it's easier than it looks, I just wanted to be thorough. We are just instructing the browser and Tampermonkey (TM) to load the script in our file system, which we'll then edit directly.
Coding to instant updates 👨‍💻
Go to Chrome => Extensions and find the TM 'card'. Click details. On the page that opens, allow it access to file URLs:
Save your script file wherever you want in your filesystem. Save the entire thing, including the ==UserScript== header. This works in all desktop OS's, but since I'm using macOS, my path will be: /Users/me/Scripts/SameWindowHref.user.js
Now, go to the TM extension's dashboard, open the script in question in its editor, and delete everything except the entire ==UserScript== header
Add to the header a #require property pointing to the script's absolute path.
At this point, TM's editor should look something like this:
Update: It seems that using the file:// URI scheme at the beginning of your path is now required. On windows systems would be:
// #require file://C:\path\to\userscript.user.js
For macOS and *nix, we'll need three slashes in a row:
// #require file:///path/to/userscript.user.js
Execution Contexts 💻 (advanced)
If you have multiple JavaScript files called with #require (like jQuery or when fragmenting a massive script into smaller pieces for a better experience), don't skip this part.
The #require paths can reference *.user.js or directly *.js files, and any UserScript-style comment headers in these files have no effect.
From the main script's ==UserScript== header, all #require files are text-concatenated in the order specified, with a single newline separating each file. This amalgamation runs as one large script. This means any global function or variable in any file will also be global in all your userscript's files, which isn't ideal.
Errors in one file may influence how subsequent files run. Additionally, to enable strict mode on all of your files, 'use strict'; must be the first statement of the first file listed with #require.
After all #require files run, your main UserScript (the one accessed by TamperMonkey's editor) is run in a separate context. If you want strict mode, you must also enable it here.
Workflow 🕺
Now every time that script matches (#match) the website you are visiting, TamperMonkey will directly load and run the code straight from the file on disk, pointed by the #require field.
I use VSCode (arguably the best multiplatform code editor ever. And free), so that's where I work on the script, but any text editor will do. It should look like this:
Notice how TM's editor and your IDE/Editor have the same header.
Every change in the code is saved automatically in VSCode, so if yours doesn't: remember to save. Then you'll have to reload the website to load the changes.
Bonus tips!
You can easily automate reloading the site on file change using a one-liner from browser-sync's CLI, to mention one tool, and have a great experience.
If you're not using git, you should consider using it with your userscripts, even if you are the sole developer. It will help keep track of your progress, sanely work on different features at the same time, roll back mistakes, and help you automatically release new updates to your users!
And please share all your creations here and here 😄
Working with GitHub or other SCMs
You have to add an #updateURL tag followed by the URL with the raw file from GitHub or whatever provider you chose. GitHub's example:
Note that a #version tag is required to make update checks work. The vast majority of users don't need the #downloadURL tag, so unless your script has a massive follower base, use #updateURL.
TM will check for updates as it's configured from the settings tab:
Externals sets how often the scripts called from your script's #require are checked to update (jQuery, for example).
You can also "force" an update check:
Using external libraries (like jQuery)
It must be present at least in TM's editor to load it. However, I recommend keeping both headers (the TM's and the file on disk's header) the same to avoid confusion. Simply #require it like this to use it:
// #require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js
Documentation
Take a look at TM's documentation page, it's very concise, and with a quick read, you'll have a clear picture of what you can do. Happy hacking! 💪
I want to publish alpha/beta release [...]
You can use the #updateURL userscript tag to point out a web URL [1] and use it along with git to achieve your need.
Here's how I implement it:
On my Gitlab instance https://foo.com/user/project/raw/develop/main.user.js points out the raw userscript file of the develop branch.
Links to develop and other important feature branches are available on the description of the project so that people can choose to follow a development version instead of the master one[2].
and I use this template for sharing:
// ==UserScript==
// #name New Userscript
// #namespace foo.com
// #version 0.3
// #description try to take over the world!
// #author user
// #match https://bar.org/*
// #grant none
// #updateURL https://foo.com/user/project/raw/develop/main.user.js
// ==/UserScript==
(function() {
'use strict';
// Your code here...
})();
Then upon triggering Check for userscript updates button on Greasemonkey or Tempermonkey, they will install the script available at this URL.
[1] Accessible one from where you want to install eg. public Github repo from your personal computer, or your companie's private Gitlab instance from your work computer
[2] note that in order to be installable upon a click on the link, the name of the file must ends with .user.js
Extension to Carles's answer
from time import *
import pathlib
from pyautogui import *
from glob import *
from pyperclip import *
import re
author='SmartManoj'
repo='SmartUserScripts'
namespace=f'https://github.com/{author}'
def local():
return f'''// ==UserScript==
// #name {name}
// #version 0.1
// #description try to take over the world!
// #author {author}
// #namespace {namespace}
// #match {link}
// #updateURL https://raw.githubusercontent.com/{author}/{repo}/master/{fn}
// ==/UserScript==
'''
def browser():
return f'''// ==UserScript==
// #name {name}
// #version 0.1
// #description try to take over the world!
// #author {author}
// #namespace {namespace}
// #match {link}
// #require {local_path}/{fn}
// #grant GM_setClipboard
// ==/UserScript==
'''
hotkey('win','3') # chrome index
hotkey('ctrl','shift','h')
fn=prompt('Enter File name')
name=prompt('Enter Script name',default=fn)
sleep(1)
hotkey('ctrl','a')
hotkey('ctrl','x')
local_path=pathlib.Path(__file__).parents[0].as_uri()
ext='.user.js'
l=len(glob(fn+ext))
if l:fn+=f'_{l+1}'
fn+=ext
a=paste()
link=re.search('#match\s*(.*)',a)[1].strip()
print(local(),file=open(fn,'w'))
copy(browser())
hotkey('ctrl','v')
Latest version
Need to do another script if header changes
Tampermonkey uses something called WebDAV to use an external editor to edit userscripts; TamperDAV.
I haven't tried it yet, but it looks like connecting with Visual Studio should be possible.
Trim21 provides, probably the best large-scale UserScript development solution so far, using webpack to cooperate LiveReloadPlugin realizes modular development and automated testing.
Here is the project.
It can use ES5/ES6 and TypeScript to develop modular scripts on IDE. It's really easy to use!
Integrated LiveReloadPlugin, you can directly refresh any #matchURL.
It is better than the previous scheme, which greatly improves the development efficiency of UserScript!
I've answered this in another question; I think someone should merge them. In the meantime, since it's I haven't seen a lot of info on this, I'll put it here for the next person looking for help.
for Mac users additional to carles answer and the #required URL - it need three slashes! Took me way too long to get it work.
#required file:///Users/me/STUFF/Code/Scripts/SameWindowHref.user.js

Greasemonkey swallows JS errors without logging them [duplicate]

I am having issues with this very basic Greasemonkey script, most likely with the metadata configuration.
Here is the full source of the basic file
// ==UserScript==
// #name Google Hello
// #namespace https://google.com
// #description Basic Google Hello
// #include *
// #version 1
// ==/UserScript==
alert("hi google!");
This script should run when I access Google.com, but the alert is not popping up. What is the issue?
I am attempting to run this script on Ubuntu with Firefox.
If alerts() are not firing, chances are you may have clicked Firefox's Prevent this page from creating additional dialogs option, or set a browser preference (older versions of Firefox), or Firefox may have become unstable in memory.
Universal Greasemonkey debug steps:
(With one step added for problems with alert().)
First make sure that the script is even firing for the page in question.
While browsing that page, click on the down-triangle next to the Greasemonkey icon (Alternatively, you can Open Tools -> Greasemonkey on the Firefox menu.) and verify that the expected script name appears and is checked. EG:
See if there are any relevant messages/errors on Firefox's Browser Console.
Activate the console by pressing CtrlShiftJ, or equivalent.
Here's a screenshot showing how both messages and errors appear in the Browser Console -- caused by both the web page and the Greasemonkey script:
Open about:config, search for capability.policy.default.Window.alert and delete or reset the value, if it is found.
Uninstall the Greasemonkey script.
Completely clear the browser cache.
Shutdown Firefox completely. Use Task Manager, or equivalent, to verify that there is no Firefox thread/task/process in memory.
Restart Firefox.
Install the Greasemonkey script afresh.
If it still doesn't work, create a new Firefox profile or try a different computer altogether.
Additional issues:
Please supply your versions of three things: (1) The OS, (2) Firefox, (3) Greasemonkey or Tampermonkey or Scriptish, etc.
#include * means that the script will fire for every page! This is almost always a poor practice. (There are some exceptions, but your case is not one.)
#namespace does not control where the page runs. The only thing #namespace does is allow more than one script to have the same name (as long as their #namespaces are different). See the #namespace documentation.
Avoid using alert() for debugging. It's annoying and can mask timing problems.
Use console.log(). You can see the results, and helpful error messages (hint, hint) on the Browser Console.
Google almost always uses/redirects to www.google.com (For English USA users). So, // #include  https://google.com will almost never work like you want.
Recommend you use:
// #match *://www.google.com/*
as a starting point.
In Firefox Greasemonkey, you can also use the magic .tld to support most of Google's international domains, like so:
// #include http://www.google.tld/*
// #include https://www.google.tld/*
Use both lines. Note that this does not perform as well as the #match line does. So, if you only care about one nation/locale, just use #match.
Putting it all together:
Uninstall your script.
Restart Firefox.
Install this script:
// ==UserScript==
// #name Google Hello
// #namespace John Galt
// #description Basic Google Hello
// #match *://www.google.com/*
// #version 1
// #grant none
// ==/UserScript==
console.log ("Hi Google!");
Visit Google and note the results on Firefox's Browser Console.
If there is still a problem, follow all of the debug steps above.
If there is still a problem, Open a new question and supply ALL of the following:
The three versions, mentioned above.
The relevant errors and messages you get on the Browser Console.
The exact code and steps needed to duplicate the problem. Make an MCVE for this!
A short summary of what you have tried to solve the problem.

Using document.evaluate in Greasemonkey [duplicate]

I am having issues with this very basic Greasemonkey script, most likely with the metadata configuration.
Here is the full source of the basic file
// ==UserScript==
// #name Google Hello
// #namespace https://google.com
// #description Basic Google Hello
// #include *
// #version 1
// ==/UserScript==
alert("hi google!");
This script should run when I access Google.com, but the alert is not popping up. What is the issue?
I am attempting to run this script on Ubuntu with Firefox.
If alerts() are not firing, chances are you may have clicked Firefox's Prevent this page from creating additional dialogs option, or set a browser preference (older versions of Firefox), or Firefox may have become unstable in memory.
Universal Greasemonkey debug steps:
(With one step added for problems with alert().)
First make sure that the script is even firing for the page in question.
While browsing that page, click on the down-triangle next to the Greasemonkey icon (Alternatively, you can Open Tools -> Greasemonkey on the Firefox menu.) and verify that the expected script name appears and is checked. EG:
See if there are any relevant messages/errors on Firefox's Browser Console.
Activate the console by pressing CtrlShiftJ, or equivalent.
Here's a screenshot showing how both messages and errors appear in the Browser Console -- caused by both the web page and the Greasemonkey script:
Open about:config, search for capability.policy.default.Window.alert and delete or reset the value, if it is found.
Uninstall the Greasemonkey script.
Completely clear the browser cache.
Shutdown Firefox completely. Use Task Manager, or equivalent, to verify that there is no Firefox thread/task/process in memory.
Restart Firefox.
Install the Greasemonkey script afresh.
If it still doesn't work, create a new Firefox profile or try a different computer altogether.
Additional issues:
Please supply your versions of three things: (1) The OS, (2) Firefox, (3) Greasemonkey or Tampermonkey or Scriptish, etc.
#include * means that the script will fire for every page! This is almost always a poor practice. (There are some exceptions, but your case is not one.)
#namespace does not control where the page runs. The only thing #namespace does is allow more than one script to have the same name (as long as their #namespaces are different). See the #namespace documentation.
Avoid using alert() for debugging. It's annoying and can mask timing problems.
Use console.log(). You can see the results, and helpful error messages (hint, hint) on the Browser Console.
Google almost always uses/redirects to www.google.com (For English USA users). So, // #include  https://google.com will almost never work like you want.
Recommend you use:
// #match *://www.google.com/*
as a starting point.
In Firefox Greasemonkey, you can also use the magic .tld to support most of Google's international domains, like so:
// #include http://www.google.tld/*
// #include https://www.google.tld/*
Use both lines. Note that this does not perform as well as the #match line does. So, if you only care about one nation/locale, just use #match.
Putting it all together:
Uninstall your script.
Restart Firefox.
Install this script:
// ==UserScript==
// #name Google Hello
// #namespace John Galt
// #description Basic Google Hello
// #match *://www.google.com/*
// #version 1
// #grant none
// ==/UserScript==
console.log ("Hi Google!");
Visit Google and note the results on Firefox's Browser Console.
If there is still a problem, follow all of the debug steps above.
If there is still a problem, Open a new question and supply ALL of the following:
The three versions, mentioned above.
The relevant errors and messages you get on the Browser Console.
The exact code and steps needed to duplicate the problem. Make an MCVE for this!
A short summary of what you have tried to solve the problem.

Error: Permission denied to access property 'handler'

I have a greasemonkey script for Firefox, which yesterday was working perfectly. I tried using it today (no code was modified) and I noticed that it stopped working. Upon further inspection, the script is now throwing the following error:
Error: Permission denied to access property 'handler'
This error is being thrown in the following block of code:
$('body').click(function() {
// code here
});
This error magically started happening today when the script was working just fine yesterday. I'm not understanding why this error is happening when just trying to do something so basic such as adding an event handler in jQuery.
My script uses jQuery which is already being used in the page the script executes on, so I used this code to make it accessible to GM:
var $ = unsafeWindow.jQuery;
For reference if need be, here are the following Greasemonkey functions I use in my script:
// #grant GM_getResourceText
// #grant GM_addStyle
// #grant GM_xmlhttpRequest
// #grant GM_getResourceURL
I have tried researching this error and I can't find any answer. All of the questions that look like they might be helpful involve iframes and there is not a single iframe to be found in my code or the website it's run on. I've also tried deleting and re-installing the script and that didn't fix the problem.
Greasemonkey 2.0 has just been pushed to all Firefox browsers set to auto-update. (GM 2 was released on June 17, 2014, but it can take a few weeks to get through the review process.)
Greasemonkey 2.0 radically changed unsafeWindow handling:
Backwards incompatible changes:
For stability, reliability, and security the privileged sandbox has been updated to match the new changes to unsafeWindow for the Add-on SDK. In order to write values to unsafeWindow you will need to use the new methods cloneInto(), exportFunction(), and/or createObjectIn().
The #grant none mode is now the default, and grants will no longer be implied when not explicitly provided. See the post Sandbox API Changes in Greasemonkey 2.0 for more detail.
Ordinarily, to spot-access a page function or variable, you could switch to the new methods but, in your case you are using var $ = unsafeWindow.jQuery; -- which was always a bad practice.
jQuery is a special case and cloning it back and forth is going to break things.
#require jQuery instead, EG:
// ==UserScript==
// #name _YOUR_SCRIPT_NAME
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// #grant GM_getResourceText
// #grant GM_addStyle
// #grant GM_xmlhttpRequest
// #grant GM_getResourceURL
// ==/UserScript==
...
You're using unsafeWindow – that, as the name suggested, is not necessary "safe" to use – the problem probably relies there; a change was made in Firefox about objects across compartments:
https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/
The blog post mention Add-on SDK, but the changes is in the platform, so it will affect Greasemonkey too.
So you basically try to get an object from one compartment (jQuery, from "unsafeWindow") and use in your greasemonkey sandbox. The way you're doing now probably can't work anymore. You can try to use the API mentioned in the article, but I'm afraid that a whole library like jQuery could have some issue to be cloned. In fact, the best way is probably load jQuery also in your Greasemonkey compartment instead of reuse the one from the page's one.
The error probably started "magically" 'cause you have updated your version of Firefox – or it gets the autoupdated.
This page explains how to load jQuery in a Greasemonkey script: http://wiki.greasespot.net/Third-Party_Libraries
The relevant parts are:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
...
this.$ = this.jQuery = jQuery.noConflict(true);
According to the docs, jQuery.noConflict() will make sure the version of jQuery for your script won't interfere with the page.
See also: jQuery in Greasemonkey 1.0 conflicts with websites using jQuery

How to convert a bookmarklet into a Greasemonkey userscript?

Is there a easy way to do this. And is there anything that needs to be changed due to differences in how it is ran?
The easiest way to do this:
Run the bookmarklet code through a URL decoder. so that javascript:alert%20('Hi%20Boss!')%3B, for example, becomes:
javascript:alert ('Hi Boss!');
Strip the leading javascript: off.   Result: alert ('Hi Boss!');
Add this code to the end of your Greasemonkey file. For example, create a file named,
Hello World.user.js, with this code:
// ==UserScript==
// #name Hello World!
// #description My first GM script from a bookmarklet
// #include https://stackoverflow.com/questions/*
// #grant none
// ==/UserScript==
alert ('Hi Boss!');
Open Hello World.user.js with Firefox (CtrlO ).   Greasemonkey will prompt to install the script.
Now the bookmarklet code will run automatically on whatever pages you specified with the #include and #exclude directives.
Update: To ensure maximum compatibility, use the #grant none directive that was added in later versions of Greasemonkey and Tampermonkey.
IMPORTANT:
The userscript will run much sooner than you could ever activate a bookmark. Normally, this is not a problem.
But in some cases, you might need to wait for some part of the page to fully load.
In that case, you can use techniques/utilities like waitForKeyElements.
See also, Choosing and activating the right controls on an AJAX-driven site .
If you still can't get your new script to work, be sure to read My very simple Greasemonkey script is not running?. Follow the steps and include the specified information in any question you open about problems with the new script.
Here is a very good article to avoid common pitfalls because of differences between "normal" JS and Greasemonkey.
The most important things at the beginning:
Do not use functions as strings, like: window.setTimeout("my_func()", 1000); but rather
window.setTimeout(my_func, 1000); or
window.setTimeout(function(){doSomething(); doSomethingOther();}, 1000);
Do not set element.onclick but rather element.addEventListener("click", my_func, true);
Some code that normally returns various DOM objects, in Greasemonkey environment returns those objects wrapped in XPCNativeWrapper. This is for security reasons.
Some methods and properties are "transparent" and you can invoke them on wrapped object, but some not. Read in the mentioned article about how to circumvent this; you can also use (this is not recommended generally, but for testing etc.) wrappedJSObject property. It is, when obj.something/obj.something() doesn't work in Greasemonkey, try obj.wrappedJSObject.something/obj.wrappedJSObject.something().

Categories