1

How can I call a Javascript function, defined in a script in the HTML page, from a user script?

I have a user script in Chromium loaded by dragging my.user.js to the chrome://extensions/ page. The script which Chromium sees as an extension is similar to this:

// ==UserScript==
// @match http://192.168.0.1/common_page/login.html
// ==/UserScript==

document.getElementById('loginPassword').value="a-password"
LoginFunc()

The script can do things like console.log('hello') fine. I am trying to call a function called LoginFunc defined on line 644 in the page HTML.

I can call LoginFunc with the Javascript console in developer tools and it does exactly what I want. Every way I have tried to call LoginFunc from my user script just gives LoginFunc is not defined though.

I have tried:

setTimeout(LoginFunc(),10000)

setTimeout(function(){
  if (typeof LoginFunc === "function") {  
    LoginFunc()
  }
},10000)

setInterval(function(){
  if (typeof LoginFunc === "function") {  
    LoginFunc()
  }
},1000)

window.onload = LoginFunc

document.addEventListener('DOMContentLoaded', LoginFunc, false);
brendan
  • 384
  • 3
  • 10
  • 1
    In what scope is LoginFunc declared? – James Gould Aug 05 '17 at 00:37
  • are you calling `LoginFunc` in a *content script* that is injected into the page? – Jaromanda X Aug 05 '17 at 00:45
  • @JayGould I'm not sure. Is it global scope? I linked to the page HTML in the question now. – brendan Aug 05 '17 at 00:52
  • [this?](https://stackoverflow.com/questions/5006460/userscripts-greasemonkey-calling-a-websites-javascript-functions) – James Aug 05 '17 at 00:53
  • a little more info about the extension would help, i.e. where in your extension are you trying to call `LoginFunc` – Jaromanda X Aug 05 '17 at 00:58
  • For Chrome Extensions, I believe [this](https://developer.chrome.com/extensions/messaging#external) is as close as you can get. – Dan Aug 05 '17 at 01:09
  • I got it to work with `location.assign("javascript:LoginFunc();void(0)")` from that @James. Thank you. Not sure if this is the best way to do it. If this is not best practice, please tell us what is. Thanks very much all – brendan Aug 05 '17 at 01:42
  • Simply [create a script element](https://stackoverflow.com/questions/9515704/insert-code-into-the-page-context-using-a-content-script) with the code you want to run in the page context. – wOxxOm Aug 05 '17 at 03:41
  • @wOxxOm script injection was mentioned in James' reference. Unless there's something wrong with using location, I think I'll use it for a simple, single call like this. It's certainly shorter. Thanks though – brendan Aug 05 '17 at 11:40
  • Well, apart from being an ancient hack, there's probably nothing wrong, if it works. – wOxxOm Aug 05 '17 at 11:41

0 Answers0