Can I run a userscript on the new tab page?

Viewed 2826

I have a very simple userscript that I've written with TamperMonkey, and I'd like it to run on the Chrome new tab page.

According to this site there is no way to run userscripts on the new tab page:

The URL of the new tab page is "chrome://newtab/" and Chrome doesn't allow extensions to inject scripts into that pages.

But my script runs fine if I specify in the header section

// @match        *://*/*

to match all pages. Still, I'd rather the code only ran on the new tab page, is this possible?


Full script:

// ==UserScript==
// @name         Hide Buttons
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Test script
// @author       Greedo
// @match        *://*/*
// @grant        none
// ==/UserScript==
(function(window, chrome) {
    "use strict";
    var doc = window.document;
    doc.getElementById("mv-tiles").style.opacity = "0";
    doc.getElementById("f").style.opacity = "0.1";
}(window, chrome));

I'm using Chrome Version 59.0.3071.115.

2 Answers

Before the script loads, inside the code put the following requirement:

if(document.URL == 'chrome://new-tab-page/'){
    // Your user script code
}

Try using the @match *://*/* and printing the window.location you'll see that the href property does not contain chrome://new-tab-page/ but https://ogs.google.com/u/0/widget/app?origin=chrome-untrusted%3A%2F%2Fnew-tab-page&origin=chrome%3A%2F%2Fnew-tab-page&cn=app&pid=1&spid=243&hl=en (in my case).

If I use chrome://new-tab-page/ the script does not work but if the other URL is used it does actually work.

Here what I used to get the URL:

// ==UserScript==
// @name         Hide Buttons
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Test script
// @author       Greedo
// @match        *://*/*
// @grant        none
// ==/UserScript==
(function() {
    "use strict";
    console.log(window.location)
}());
Related