Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am a newbie in javascript and java programming. I have a .java file with a function updateInfo(). I want to call that function in my .js file. How can I do that? Please help. Thanks!!!
Yes, you can, but not directly.
One option is to use a JAX-RS implementation like Apache CXF or Jersey. Once you have created a RESTful web service that maps to the method in your Java file, you can use JavaScript to make an AJAX call. Thus, you can certainly call a Java method via JavaScript in a form of a RESTful web service.
First make sure your java is compiled to jar (and extends applet / japplet)
You can invoke javascript functions with netscape.javascript.*
Example HTML
<head>
<title>Data Summary Applet Page - Java to JavaScript LiveConnect</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script language="javascript">
var userName = "";
// returns number
function getAge() {
return 25;
}
// returns an object
function address() {
this.street = "1 Example Lane";
this.city = "Santa Clara";
this.state = "CA";
}
// returns an array
function getPhoneNums() {
return ["408-555-0100", "408-555-0102"];
}
function writeSummary(summary) {
summaryElem =
document.getElementById("summary");
summaryElem.innerHTML = summary;
}
</script>
<!-- ... -->
</head>
<body>
<script src =
"http://www.java.com/js/deployJava.js"></script>
<script>
<!-- ... -->
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<!-- ... -->
<p id="summary"/> // this HTML element contains
// the summary
<!-- ... -->
</body>
Example java implementation:
package javatojs;
import java.applet.Applet;
import netscape.javascript.*; // add plugin.jar to classpath during compilation
public class DataSummaryApplet extends Applet {
public void start() {
try {
JSObject window = JSObject.getWindow(this);
String userName = "John Doe";
// set JavaScript variable
window.setMember("userName", userName);
// invoke JavaScript function
Number age = (Number) window.eval("getAge()");
// get a JavaScript object and retrieve its contents
JSObject address = (JSObject) window.eval("new address();");
String addressStr = (String) address.getMember("street") + ", " +
(String) address.getMember("city") + ", " +
(String) address.getMember("state");
// get an array from JavaScript and retrieve its contents
JSObject phoneNums = (JSObject) window.eval("getPhoneNums()");
String phoneNumStr = (String) phoneNums.getSlot(0) + ", " +
(String) phoneNums.getSlot(1);
// dynamically change HTML in page; write data summary
String summary = userName + " : " + age + " : " +
addressStr + " : " + phoneNumStr;
window.call("writeSummary", new Object[] {summary}) ;
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
More information about invoking javascript from java
More information about invoking java methods from javascript
You can't directly call a java method from JavaScript. Equals whether the java Code is Compiled or not.
To bind Java code with JavaScript you must create first Applet. Only after, there are several techniques to invoke JavaScript from Applet and vice versa
Related
I want to load/read and edit/modify and save a html file located on my hard drive. I tried JSOUP, but it kept reformatting the html file. I want to avoid reformating.
I'm wanting to inject some JavaScript after the <script> and before var deviceReady = false; in the html file.
Do I need to parse the file?
Should I use default Java? (BufferedReader, FileReader, Scanner)
<!DOCTYPE html>
<html lang="en">
<head>
<meta name='viewport' content='initial-scale = 1, minimum-scale = 1, maximum-scale = 1'/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="x-ua-compatible" content="IE=10">
<title>LX-XXX-KU</title>
<style type="text/css">#initialLoading{background:url(assets/htmlimages/loader.gif) no-repeat center
center;background-color:#ffffff;position:absolute;margin:auto;top:0;left:0;right:0;bottom:0;z-
index:10010;}</style>
"
<script>
var deviceReady = false;
var initCalled = false ;
var initialized = false;
function onBodyLoad()
{
if(typeof window.device === 'undefined')
{
document.addEventListener("deviceready", onDeviceReady, false);
}
else
{
onDeviceReady();
}
}
Javasacript I want to add after the <script> and before var deviceReady = false;
`//adds numbers to TOC
window.addEventListener( 'moduleReadyEvent', function ( e )
{
var myText = document.getElementsByClassName('tocText');
for ( var i = 0; i < myText.length; i++ )
{
var getText = myText[ i ].childNodes;
var str = ( i + 1 ) + ' ' + getText[ 0 ].innerHTML;
getText[ 0 ].innerHTML = str;
}
});`
This can be accomplished like so:
File f = ...;
String contents = new String(Files.readAllBytes(f));
int idx = contents.indexOf(insertBeforeStr);
contents = contents.substring(0, idx) + contentToBeAdded + contents.substring(idx + 1);
// write contents back to the disk.
If you turn off jsoup's pretty printing option, and use the XML parser instead of the validating HTML parser, the document and all of its text verbatim, including whitespace, is passed through pretty much unmolested, other than syntax fixes for attributes, missing end tags, and the like.
See for example your input on Try jsoup with pretty-printing off, and using the XML parser, is effectively the same as your original.
The code would be something like:
Document doc = Jsoup.parse("<script>\nSomething(); ", "", Parser.xmlParser());
doc.outputSettings().prettyPrint(false);
Element scriptEl = doc.selectFirst("script");
DataNode scriptData = scriptEl.dataNodes().get(0);
scriptData.setWholeData(scriptData.getWholeData() + "\nanotherFunction();");
System.out.println(doc.html());
Gives us (note that there's no HTML structure automatically created, due to using the XML parser):
<script>
Something();
anotherFunction()</script>
ControlAltDel's answer definitely works and means you can do it with just the Java base library. The benefit of using jsoup is (IMHO - as the author of jsoup) in this case is that you're not trying to string-match HTML, and won't get caught by e.g. a <script> in a comment, or in this case a missing close </script> tag, etc. But of course YMMV.
Incidentally, once jsoup 1.14.1 is released (soon!) with the change #1419 (which for script elements, proxies text settings into data without escaping), the code will simplify to:
Element scriptEl = doc.selectFirst("script");
scriptEl.appendText("\nanotherFunction()");
I need to get text value as indicated below:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<b>Some Text I can find using xPath</b>
<hr>
**TEXT I WOULD LIKE TO FIND THAT IS BEING ADDED DYNAMICALLY - it will be different number every time page loads**
<hr>
**some other text dynamically added**
</body>
</html>
I tried by using
driver.findElement(By.xpath("/html/body/text()[1]"));
with no luck.
It's not straight forward due to the WebDriver not handling anything but element nodes. I opened a while ago two issues: one against the WebDriver and another one against the W3C WebDriver specification. (vote for them if, it helps showing a need of the user base).
Meanwhile, as a (painful) workaround, you will need to rely on JavascriptExecutor capabilities of your WebDriver. An example (in another context, thus will have to be adapted to your specifics), in one of my older answers.
Adapted to your case, with the note it may contain bugs cause by typos (I haven't checked it):
WebElement contextNode=driver.findElement(By.xpath("/html/body"));
if(driver instanceof JavascriptExecutor) {
String jswalker=
"var tw = document.createTreeWalker("
+ "arguments[0],"
+ "NodeFilter.SHOW_TEXT,"
+ "{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT;} },"
+ "false"
+ ");"
+ "var ret=null;"
// skip over the number of text nodes indicated by the arguments[1]
+ "var skip;"
+ "for(skip=0; tw.nextNode() && skip<arguments[1]; skip++);"
+ "if(skip==arguments[1]) { " // found before tw.nextNode() ran out
+ "ret=tw.currentNode.wholeText.trim();"
+ "}"
+ "return ret;"
;
int textNodeIndex=3; // there will be empty text nodes before after <b>
Object val=((JavascriptExecutor) driver).executeScript(
jswalker, contextNode, textNodeIndex
);
String textThatINeed=(null!=val ? val.toString() : null);
}
Please let me know if/how it works.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to call a JavaScript function testCheckMate from Java but I get error:
Exception in thread "JavaFX Application Thread" netscape.javascript.JSException: SyntaxError: Unexpected EOF
The WebView is holding FullCalendar.
How do I go about calling JQuery/ Javascript from Java? Thank you all in advance.
<!DOCTYPE html>
<html>
<head>
<link href='../fullcalendar/fullcalendar.css' rel='stylesheet' />
<link href='../fullcalendar/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='../lib/jquery.min.js'></script>
<script src='../lib/jquery-ui.custom.min.js'></script>
<script src='../fullcalendar/fullcalendar.min.js'></script>
<script>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
editable: true,
testCheckMate: function() {
alert("Check-Mate");
},
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false
}
]
});
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
If I get this right, you want to send some data from JavaScript when the user clicks on some of the items of the calendar.
First, you should give a name to the JavaScript property different from the actual name of function eventClick, like: myClick. Then pass a new instance of JavaApp:
script.setMember("myClick", new JavaApp());
where JavaApp should be public, and its method should receive the messages from JS. (EDIT: You can define several arguments):
public class JavaApp {
public void javaApp(String title, String x, String y, String name) {
System.out.println("Event Title: "+title+", Coordinates ("+x+", "+y+"), view Name: "+name);
}
}
Finally, on the JavaScript side, inside the eventClick function, use the JS property sent from JavaFX and its method to send the data to the Java side:
eventClick: function(calEvent, jsEvent, view) {
myClick.javaApp(calEvent.title, jsEvent.pageX, jsEvent.pageY, view.name);
// change the border color just for fun
$(this).css('border-color', 'red');
};
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.
This is the list I'm trying to send/access:
List<MarkerClass> markers;
MarkerClass is defined acoprding to belove:
final class MarkerClass
{
public Integer objectId;
public String street;
public String streetNumber;
public String zip;
public String city;
public Integer statusId;
public Float lattitude;
public Float longitude;
}
The action also includes a getter for markers:
public List<MarkerClass> getMarkers()
{
return markers;
}
In my jsp-file I have tried doing this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ "${markers[i].street}";
}
}
The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass#37a4, se.fubar.test.MarkerClass#9ad97c]"
I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):
function initialize() {
var title = "";
<c:foreach var="marker" list="${markers}">
title = title + "${marker.street}";
</c:foreach>
}
Something along those lines anyway... Basically the Javascript seen by your browser will look like
function initialize() {
var title = "";
title = title + "Street1";
title = title + "Street2";
title = title + "Street3";
title = title + "Street4";
}
I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so
var myVar= '<c:out value="${requestScope.myVar}"/>';
then use the var inside your js.
In case you set an object in request or session you have to use the get method to access the value of an attribute then use it like so:
var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';
(assuming you getter method is getAttribute)
it is not possible to access data in session or request directly from js
hope this helps
You could convert the object to json on the server (see http://www.json.org/java/index.html ) and then call eval() on the string to get a javascript representation of your object.
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ <s:property value="%{markers.get(i).street}">;
}
}
just try it since OGNL has capacity to access the object on the value stack
looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>