简体   繁体   English

从Java代码调用网站的javascript函数?

[英]Invoke a javascript function of a website from java code?

Is it possible to use java code to invoke a javascript function that is in the sourcecode of a website? 是否可以使用Java代码来调用网站源代码中的javascript函数?

Imagine a website with following code: 想象一个带有以下代码的网站:

<script>
 function sayHello(name) {
    return "Hello " + name;
}
</script>

Could I call "sayHello" from a client connecting to that webpage? 我可以从连接到该网页的客户端调用“ sayHello”吗? (I know I could call javascript from java if I have the *.js file locally saved. But I don't want this as the JS might change on the website I want to invoke the function). (我知道如果我将* .js文件保存在本地,则可以从Java调用javascript。但是我不希望这样做,因为JS可能会在我要调用该函数的网站上更改)。

 ScriptEngineManager factory = new ScriptEngineManager();
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 engine.eval(..); //is it possible to invoke the JS function on the website?

I think you would have to parse content of script tags first (manually by fetching HTML page and then using eg RegExp find content of all script elements) and then pass it to the eval() as a string. 我认为您必须首先解析脚本标签的内容(通常是通过获取HTML页面,然后使用RegExp查找所有脚本元素的内容),然后将其作为字符串传递给eval()。 Not pretty thing is that the JS code in <script> could be using some other JS code (external, loaded before this element etc.) so you might need to check for these "dependencies" as well. 不太漂亮的是, <script>中的JS代码可能正在使用其他一些JS代码(外部的,在此元素之前加载的等等),因此您可能还需要检查这些“依赖项”。

您只能通过Ajax calliframe refresh之类的老式方式来做到这一点

If I understood correctly you want to call existing JavaScript in website as well as add some logic yourself. 如果我理解正确,那么您想调用网站中的现有JavaScript以及自己添加一些逻辑。

You don't have to use Java here at all, you can simply inject your JavaScript into that page by 您根本不需要在这里使用Java,只需将JavaScript注入该页面即可,方法是:

  1. bookmarklets 小书签

  2. Browser extenstions I'd recommend Kango 浏览器扩展我会推荐Kango

  3. Or simply pasting the code into the browser console 或者只是将代码粘贴到浏览器控制台中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM