3

I am trying to use this line of JavaScript as a GreaseMonkey script:

javascript: document.getElementsByClassName("widget-contents")[0].style.height='640px';void(0);

I tried to convert it into a GreaseMonkey script as such:

// ==UserScript==
// @name        First GM Script
// @namespace   http://www.example.net/
// @description first gm script
// @include     https//www.example.net/*
// @version     1
// @grant       none
// ==/UserScript==
document.getElementsByClassName('widget-contents') [0].style.height = '640px';

and I am getting this error:

document.getElementsByClassName(...)[0] is undefined

Could someone explain to me what am I doing wrong?

mkolarek
  • 527
  • 1
  • 7
  • 16
  • Your script is probably running before element you've looking for is rendered. Check GM start time options or otherwise delay execution. – Oleg V. Volkov Feb 09 '16 at 10:13
  • @Oleg I tried adding `// @run-at document-end` and `document-idle` but that didn't work. – mkolarek Feb 09 '16 at 10:27
  • @kolarek can you try `document.querySelector('widget-contents').style.height = ...`, if you will get same-ish error, than indeed you are requesting the element that does not exist yet – euvl Feb 09 '16 at 10:31

2 Answers2

2

Try

document.onload = function() {
  document.getElementsByClassName('widget-contents') [0].style.height = '640px';
}
euvl
  • 4,716
  • 2
  • 25
  • 30
0

As suggested by @Oleg I tried to delay the execution of my code, finally this is the whole code:

function enlarger () {
    document.getElementsByClassName('widget-contents') [0].style.height = '640px';
}
setTimeout (enlarger, 2000);

thus delaying the execution of enlarger by 2 seconds.

mkolarek
  • 527
  • 1
  • 7
  • 16