0

My aim is to write a Tampermonkey script that puts the Clippy assistant from Microsoft Office on any webpage I choose. For this, I am using https://github.com/pi0/clippyjs. Here is what I've got so far:

// ==UserScript==
// @name        Clippy!
// @include     https://stackoverflow.com/questions/*
// @require     https://unpkg.com/jquery@3.2.1/dist/jquery.js
// @require     https://unpkg.com/clippyjs@0.0.3/dist/clippy.js
// @grant       GM_addStyle
// ==/UserScript==

/*--- For this to work well, we must also add-in the jQuery-UI CSS.
    We add the CSS this way so that the embedded, relatively linked images load correctly.
    (Use //ajax... so that https or http is selected as appropriate to avoid "mixed content".)
*/
$("head").append (
    '<link '
  + 'href="//gitcdn.xyz/repo/pi0/clippyjs/master/assets/clippy.css" '
  + 'rel="stylesheet" type="text/css">'
);

clippy.load('Merlin', function(agent){
    // Do anything with the loaded agent
    agent.show();
});

This results in:

Uncaught ReferenceError: clippy is not defined

Is there any way to make Clippyjs work as a Tampermonkey script?

Ry-
  • 218,210
  • 55
  • 464
  • 476
trumad
  • 9
  • 1

1 Answers1

0

Clippyjs is not well designed for Tampermonkey scripts, it ajaxes in other JS files like agent.js that expect clippy to be defined in the page's window scope.

This means that you must inject everything into the page's scope, like so:

// ==UserScript==
// @name        Clippy script demo injection
// @include     https://stackoverflow.com/questions/*
// @grant       none
// ==/UserScript==
/* global $, clippy */
/* eslint-disable no-multi-spaces */

//-- These particular target page(s) already have jQuery, otherwise addJS_Node() it too.

$("head").append ( `
    <link  href="//gitcdn.xyz/repo/pi0/clippyjs/master/assets/clippy.css"
    rel="stylesheet" type="text/css">
` );

addJS_Node (null, "https://unpkg.com/clippyjs@latest", null, startClippy);

//-- addJS_Node waits for clippyjs to load before running this... 
function startClippy () {
    clippy.load ('Merlin', function (agent) {
        agent.show ();
    } );
}

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}
Brock Adams
  • 90,639
  • 22
  • 233
  • 295