Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display the output of my userscript in a floating box on the side of the page?

I'm working on a userscript for Unicreatures that keeps track of events during exploration. It's working (well, it works but still needs some work lol) but I need a way to display the information I'm collecting that doesn't involve popup alerts for every step.

How can I create a box on the page and display stuff in it?

I'm looking to create a frame, window, whatever on the left side of the menu on this page, and write the values of various variables into it as my script runs.

I'm collecting this data in localStorage, so my script will first update various localStorage properties and then display the results in this box somehow:

localStorage.steps = Number(localStorage.steps) + 1;
displayValueInFloatingBox(localStorage.steps + ' in Sargasso' );

I'd also like to add a button to this box to reset the values of these properties, so that I have a choice of keeping track forever or just for a session or two without having to edit the script every time (especially if I decide to share the script). I assume this would just set the variables to zero so I just need to know how to create the button and making it do something... This would probably use an eventListener somehow.

Please stick to plain JavaScript, no jQuery... I'm still barely getting JavaScript at the moment. And please, explain answers so I understand how something works - I don't just want code snippets that leave me coming back with a similar question because I don't understand why a bit of code was used.

Appendix A: my current script

// ==UserScript==
// @name Unicreatures Egg pop-up
// @namespace Unicreatures Egg pop-up
// @description Unicreatures Egg pop-up
// @include http://unicreatures.com/explore.php*
// @include http://www.unicreatures.com/explore.php*
// ==/UserScript==
var regexp = /You find an? (Exalted )?(.*?) egg nearby/;
var match = regexp.exec( document.body.innerHTML );
if ( match ) {
  if ( match[1] ) {
      alert( "Exalted egg found: " + match[2] );
  } else {
      alert( "Normal egg found: " + match[2] );
  }
}
var y = document.body.innerHTML;
var links = document.getElementsByTagName( 'a' );

for ( var i = 0; i < links.length; i++ ) {
var link = links[i];
if ( /area=sea(?!\&gather)/.test( link.href )) {
      link.addEventListener( 'click', function () {
      localStorage.steps=Number(localStorage.steps)+1
      // alert(localStorage.steps + ' in Sargasso' );
    }, true );
  }
}

//document.addEventListener('click', function(){alert('page clicked')}, true);

if(y.indexOf("You find a Noble")> 0)
{
  alert('Noble Egg Alert');
}

if(y.indexOf("You find an Exalted")> 0)
{
  localStorage.exaltedEggCount=Number(localStorage.exaltedEggCount)+1;
  alert('Exalted Egg Alert '+localStorage.exaltedEggCount);
}

if(y.indexOf("egg nearby!")> 0)
{
  localStorage.eggCount=Number(localStorage.eggCount)+1;

  alert('Egg Alert '+localStorage.eggCount);
}
like image 292
Kat Cox Avatar asked Dec 27 '22 18:12

Kat Cox


1 Answers

Here's one simple way to add a box to the top left corner of the page. First, we need to create a div element to serve as the box. (Other HTML elements could work too, but div is a good choice since it has no special meaning, it's just a simple container.)

var box = document.createElement( 'div' );

We'll give our box an ID, both so that we can find it later with document.getElementsById() and so that we can style it with CSS:

box.id = 'myAlertBox';

Now we need to style the box. Since we're using GreaseMonkey, we can use GM_addStyle to add CSS style rules to the document:

GM_addStyle( 
    ' #myAlertBox {             ' +
    '    background: white;     ' +
    '    border: 2px solid red; ' +
    '    padding: 4px;          ' +
    '    position: absolute;    ' +
    '    top: 8px; left: 8px;   ' +
    '    max-width: 400px;      ' +
    ' } '
);

Note the awkward syntax for including a multi-line string in JavaScript. (There are other ways to style the box, too, which will work also outside GreaseMonkey. I'll show some of the them below.)

Looking at the CSS style rule itself, the first three lines just say that our box should have a white background and a two pixels wide red border, and that there should be four pixels of padding between the border and the content. All this just makes it look like a typical simple alert box.

The following line says that our box should be absolutely positioned on the page — that is, always in a fixed position regardless of what else is on the page — and the one below that specifies the position we want to give it: here, four pixels from the top left corner of the page. The last line just says that the box should not stretch to be more than 400 pixels wide, no matter how much content we stuff into it.

Speaking of which, of course we need to add some content too. We can either just use plain text:

box.textContent = "Here's some text! This is not HTML, so <3 is not a tag.";

or we can use HTML:

box.innerHTML = "This <i>is</i> HTML, so &lt;3 needs to be escaped.";

Finally, we need to add the box to the page to make it show up:

document.body.appendChild( box );

And there you go! A box on the page.


OK, but how do we get rid of it? Well, the simplest way would be to just make it disappear when clicked:

box.addEventListener( 'click', function () {
    box.parentNode.removeChild( box );
}, true );

Alternatively, we could create a separate close button for the box and set the click handler only for that:

var closeButton = document.createElement( 'div' );
closeButton.className = 'myCloseButton';
closeButton.textContent = 'X';

GM_addStyle( 
    ' .myCloseButton {           ' +
    '    background: #aaa;       ' +
    '    border: 1px solid #777; ' +
    '    padding: 1px;           ' +
    '    margin-left: 8px;       ' +
    '    float: right;           ' +
    '    cursor: pointer;        ' +
    ' } '
);

box.insertBefore( closeButton, box.firstChild );
closeButton.addEventListener( 'click', function () {
    box.parentNode.removeChild( box );
}, true );

Inserting the close button before any other content in the box, and giving it the style float: right makes it float to the top right corner and makes text flow around it. The cursor: pointer rule makes the mouse cursor look like a hand when over the button, showing that it's clickable.

You can also add other buttons to the box (or elsewhere on the page) in the same way. I gave the button a class name instead of an ID so that, if you want, you can give all your buttons the same class and they'll be style the same way.

It's also possible to just put the HTML code for the buttons in box.innerHTML, find the resulting elements e.g. with box.getElementById() and add the click handlers for them that way.


I said I'd mention other ways of styling elements. One simple way is to just write the CSS rules directly into its style property:

box.style.cssText =
    ' background: white;     ' +
    ' border: 2px solid red; ' +
    ' padding: 4px;          ' +
    ' position: absolute;    ' +
    ' top: 8px; left: 8px;   ' +
    ' max-width: 400px;      ' ;

(This way, we wouldn't even need to give the box an ID.) It's also possible to set (and read) the styles one at a time:

box.style.background = 'white';
box.style.border = '2px solid red';
box.style.padding = '4px';
box.style.position = 'absolute';
box.style.top = '8px';
box.style.left = '8px';
box.style.maxWidth = '400px';

You'll note that some of the names are different; for example, max-width would not be a valid JavaScript property name, so it becomes maxWidth instead. The same rule works for other CSS property names with hyphens.

Still, I prefer GM_addStyle because it's more flexible. For example, if you wanted to make all links inside your box red, you could just do:

GM_addStyle( 
    ' #myAlertBox a {  ' +
    '    color: red;   ' +
    ' } '
);

By the way, here's a neat trick: if you replace position: absolute with position: fixed, then the box will not scroll along with the page — instead it'll stay fixed to the corner of your browser even if you scroll down.

Another tip: If you don't have Firebug yet, install it. It will make examining page content and debugging JavaScript so much easier.

like image 163
Ilmari Karonen Avatar answered Jan 25 '23 23:01

Ilmari Karonen