Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading page and executing JS on it...from JS bookmarklet?

Essentially I'm trying to

  1. navigate to a webpage
  2. wait for that webpage to load
  3. execute a JS function/alert/whatever on that page

all from a single bookmarklet. Is this possible? I can't seem to get onload to work for me, but that may be because of my own personal failings here.

like image 619
scikidus Avatar asked Feb 15 '10 17:02

scikidus


3 Answers

The simplest way I found to do this without needing Greasemonkey or something similar is to write your JS so that it checks to see if it is on the appropriate page, and goes there if it isn't. If it is on the page, then it executes the JS/alert/whatever. You have to use the bookmarklet twice, but you just need one bookmarklet, and it may still be quicker/easier the user doing the clicking/whatevering him or herself. So the code would look like this:

if(this.document.location.href != "[url]") { //Are we on the page yet? 
  this.document.location.href = "[url]"; // If not, go there
}
else {
  if (document.readyState === "complete") { //Wait for the page to finish loading
   // DO STUFF
  }
}
like image 108
Rebecca Avatar answered Oct 15 '22 02:10

Rebecca


You want to install the Greasemonkey extension for Firefox. (or gm4ie for IE, or greasemetal for Chrome (PersonalizedWeb also works in a much simpler way for Chrome), greasekit for Safari, or user.js for Opera)

Greasemonkey lets you do exactly this... run a script automatically on every page load (you can choose what pages/sites it loads on)

Otherwise you will need to click your bookmarklet on every page load in order to run your script.

like image 33
scunliffe Avatar answered Oct 15 '22 02:10

scunliffe


Given there's no better solution, I thought I'd toss out that Opera natively supports user scripts to run on every page load. From there, you could have the script check the current url, and run if on appropriate page.

See here for documentation

like image 2
David Hobs Avatar answered Oct 15 '22 02:10

David Hobs