I want to be able to insert a Java applet into a web page dynamically using a Javascript function that is called when a button is pressed. (Loading the applet on page load slows things down too much, freezes the browser, etc...) I am using the following code, which works seamlessly in FF, but fails without error messages in IE8, Safari 4, and Chrome. Does anyone have any idea why this doesn't work as expected, and how to dynamically insert an applet in a way that works in all browsers? I've tried using document.write() as suggested elsewhere, but calling that after the page has loaded results in the page being erased, so that isn't an option for me.
function createPlayer(parentElem)
{
// The abc variable is declared and set here
player = document.createElement('object');
player.setAttribute("classid", "java:TunePlayer.class");
player.setAttribute("archive", "TunePlayer.class,PlayerListener.class,abc4j.jar");
player.setAttribute("codeType", "application/x-java-applet");
player.id = "tuneplayer";
player.setAttribute("width", 1);
player.setAttribute("height", 1);
param = document.createElement('param');
param.name = "abc";
param.value = abc;
player.appendChild(param);
param = document.createElement('param');
param.name = "mayscript";
param.value = true;
player.appendChild(param);
parentElem.appendChild(player);
}
document.write()
Will overwrite your entire document. If you want to keep the document, and just want an applet added, you'll need to append it.
var app = document.createElement('applet');
app.id= 'Java';
app.archive= 'Java.jar';
app.code= 'Java.class';
app.width = '400';
app.height = '10';
document.getElementsByTagName('body')[0].appendChild(app);
This code will add the applet as the last element of the body tag. Make sure this is run after the DOM has processed or you will get an error. Body OnLoad, or jQuery ready recommended.
I would have suggested doing something like what you're doing; so I'm baffled as to why it's not working.
Here's a document that looks pretty authoritative, coming from the horse's mouth as it were. It mentions the idiosyncrasies of different browsers. You may end up needing to do different tag soups for different implementations.
But maybe there's something magic about applet/object tags that keeps them from being processed if inserted dynamically. Having no more qualified advice, I have a crazy workaround to offer you: Howzabout you present the applet on a different page, and dynamically create an IFRAME to show that page in the space your applet should occupy? IFRAMEs are a bit more consistent in syntax across browsers, and I'd be surprised if they were to fail the same way.
Maybe you should use your browser's debugging tools to look at the DOM after you swap in your applet node. Maybe it's not appearing where you think it is, or not with the structure you think you're creating. Your code looks OK to me but I'm not very experienced with dynamic applets.
There is a JavaScript library for this purpose:
http://www.java.com/js/deployJava.js
// launch the Java 2D applet on JRE version 1.6.0
// or higher with one parameter (fontSize)
<script src=
"http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {code:'java2d.Java2DemoApplet.class',
archive:'http://java.sun.com/products/plugin/1.5.0/demos/plugin/jfc/Java2D/Java2Demo.jar',
width:710, height:540} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
</script>
I did something similar to what Beachhouse suggested. I modified the deployJava.js like this:
writeAppletTag: function(attributes, parameters) {
...
// don't write directly to document anymore
//document.write(startApplet + '\n' + params + '\n' + endApplet);
var appletString = startApplet + '\n' + params + '\n' + endApplet;
var divApplet = document.createElement('div');
divApplet.id = "divApplet";
divApplet.innerHTML = appletString;
divApplet.style = "visibility: hidden; display: none;";
document.body.appendChild(divApplet);
}
It worked ok on Chrome, Firefox and IE. No problems so far.
I tried at first to have a div already created on my html file and just set its innerHTML to the appletString, but only IE were able to detect the new applet dynamically. Insert the whole div direclty to the body works on all browsers.
Create a new applet element and append it to an existing element using appendChild.
var applet = document.createElement('applet');
applet.id = 'player';
...
var param = document.createElement('param');
...
applet.appendChild(param);
document.getElementById('existingElement').appendChild(applet);
Also, make sure the existing element is visible, meaning you haven't set css to hide it, otherwise the browser will not load the applet after using appendChild. I spent too many hours trying to figure that out.
This worked for me:
// my js code
var app = document.createElement('applet');
app.code= 'MyApplet2.class';
app.width = '400';
app.height = '10';
var p1 = document.createElement('param');
p1.name = 'sm_UnwindType';
p1.value='200';
var p2 = document.createElement('param');
p2.name = 'sm_Intraday';
p2.value='300';
app.appendChild(p1);
app.appendChild(p2);
var appDiv = document.getElementById('applet_div');
appDiv.appendChild(app);
-----html code:
<div id="applet_div"></div>
Related
I'm trying to make a program that checks avaliable positions and books the first avaliable one. I started writing it and i ran into a problem pretty early.
The problem is that when I try to connect with the site (which is https) the program doesn't do anything. It doesn't throw an error, it doesn't crash. And the weirdest thing is that it works with some https websites and with some it doesn't.
I've spent countless hours trying to resolve this problem. I tried using htmlunitdriver and it still doesn't work. Please help.
private final WebClient webc = new WebClient(BrowserVersion.CHROME);
webc.getCookieManager().setCookiesEnabled(true);
HtmlPage loginpage = webc.getPage(loginurl);
System.out.println(loginpage.getTitleText());
I'm getting really frustrated with this. Thank you in advance.
As far as i can see this has nothing to do with HttpS. It is a good idea to do some traffic analysis using Charles or Fiddler.
What you can see....
The page returned from the server as response to your first call to https://online.enel.pl/ loads some external javascript. And then the story begins:
This JS looks like
(function() {
var z = "";
var b = "766172205f3078666.....";
eval((function() {
for (var i = 0; i < b.length; i += 2) {
z += String.fromCharCode(parseInt(b.substring(i, i + 2), 16));
}
return z;
})());
})();
As you can see someone likes to hide the real javascript that gets processed.
Next step is to check the javascript after this simple decoding
It is really huge and looks like this
var _0xfbfd = ['\x77\x71\x30\x6b\x77 ....
(function (_0x2ea96d, _0x460da4) {
var _0x1da805 = function (_0x55e996) {
while (--_0x55e996) {
_0x2ea96d['\x70\x75\x73\x68'](_0x2ea96d['\x73\x68\x69\x66\x74']());
}
};
.....
Ok now we have obfuscated javascript. If you like you can start with http://ddecode.com/hexdecoder/ to get some more readable text but this was the step where i have stopped my analysis. Looks like this script does some really bad things or someone still believes in security by obscurity.
If you run this with HtmlUnit, this codes gets interpreted - yes the decoding works and the code runs. Sadly this code runs endless (maybe because of an error or some incompatibility with real browsers).
If you like to get this working, you have to figure out, where the error is and open an bug report for HtmlUnit. For this you can simply start with a small local HtmlFile and include the code from the first external javascript. Then add some log statements to get the decoded version. Then replace this with the decoded version and try to understand what is going on. You can start adding alert statements and check if the code in HtmlUnit follows the same path as browsers do. Sorry but my time is to limited to do all this work but i really like to help/fix if you can point to a specific function in HtmlUnit that works different from real browsers.
Without the URL that you are querying it is dificult to say what could be wrong. However, having worked with HTML unit some time back I found that it was failing with many sites that I needed to get data from. The site owners will do many things to avoid you using programs to access them and you might have to resort to using some lower level library like Apache HTTP components where you have more control over what is going on under the hood.
Also check if the website is constructed using JavaScript which is getting more and more popular but making it increasingly dificult to use programs to interrogate the content.
What can I do in case if I load the page in Selenium and then I have to do like 100 different parsing requests to this page?
At this moment I use different driver.findElement(By...) and the problem is that every time it is a http (get/post) request from java into selenium. From this case one simple page parsing costs me like 30+ seconds (too much).
I think that I must get source code (driver.getPageSource()) from first request and then parse this string locally (my page does not change while I parse it).
Can I build some kind of HTML object from this string to keep working with WebElement requests?
Do I have to use another lib to build HTML object? (for example - jsoup) In this case I will have to rebuild my parsing requests from webelement's and XPath.
Anything else?
When you call findElement, there is no need for Selenium to parse the page to find the element. The parsing of the HTML happens when the page is loaded. Some further parsing may happen due to JavaScript modifications to the page (like when doing element.innerHTML += ...). What Selenium does is query the DOM with methods like .getElementsByClassName, .querySelector, etc. This being said, if your browser is loaded on a remote machine, things can slow down. Even locally, if you are doing a huge amount of round-trip to between your Selenium script and the browser, it can impact the script's speed quite a bit. What can you do?
What I prefer to do when I have a lot of queries to do on a page is to use .executeScript to do the work on the browser side. This can reduce dozens of queries to a single one. For instance:
List<WebElement> elements = (List<WebElement>) ((JavascriptExecutor) driver)
.executeScript(
"var elements = document.getElementsByClassName('foo');" +
"return Array.prototype.filter.call(elements, function (el) {" +
" return el.attributes.whatever.value === 'something';" +
"});");
(I've not run the code above. Watch out for typos!)
In this example, you'd get a list of all elements of class foo that have an attribute named whatever which has a value equal to something. (The Array.prototype.filter.call rigmarole is because .getElementsByClassName returns something that behaves like an Array but which is not an Array so it does not have a .filter method.)
Parsing locally is an option if you know that the page won't change as you examine it. You should get the page's source by using something like:
String html = (String) ((JavascriptExecutor) driver).executeScript(
"return document.documentElement.outerHTML");
By doing this, you see the page exactly in the way the browser interpreted it. You will have to use something else than Selenium to parse the HTML.
Maybe try evaluating your elements only when you try to use them?
I dont know about the Java equivalent, but in C# you could do something similar to the following, which would only look for the element when it is used:
private static readonly By UsernameSelector = By.Name("username");
private IWebElement UsernameInputElement
{
get { return Driver.FindElement(UsernameSelector); }
}
basically my problem is when I want to mix javascript with java code since I did not take the variable (var nombreRodamiento javascript) when I put the "<%" to start putting java code.
please note the bold line, which is what the compiler does not like.
<script type="text/javaScript">
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {//izquierda
if (listLeft.options.length == 0) {
alert('Ya aprobaste todos los items');
return false;
} else {
var rodamientoElegido = listLeft.options.selectedIndex;
var nombreRodamiento = listLeft.options[rodamientoElegido].text;
move(listRight, listLeft.options[rodamientoElegido].value,
listLeft.options[rodamientoElegido].text);
listLeft.remove(rodamientoElegido);
<%
**String nombreRodamiento = '%> nombreRodamiento;<%'**
for (int i=0;i<listaItems.size();i++){
if (listaItems.get(i).equals(nombreRodamiento))
listaItems.remove(i);
}
%>
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
}
}
</script>
Regards
Assuming that this is all inside of a JSP. The java code (scriptlet, everything inside the <% %> tags) will execute server side, and the javascript will execute client side (in the user's browser). Yet you seem to be assigning a java variable the value of a javascript variable, nombreRodamiento. That is not going to work. The javascript is just text, with no values, execution context, etc, whenever the scriplet is being evaluated.
Java strings require double quotes, and you're missing a semicolon, which Java will not automatically insert.
Assuming this is a part of jsp file java code and js code executes separately. first java code get execute on server side and then the javascript code and that is on client side. Infact the java scriplet in jsp renderes the js code to be executed later on client which in this case is a browser.
Hence one cannot assign javascript variable value to a java variable but the reverse is possible.T
Edit:
I can give you the steps as I dont know your server side implementation.
render the page. You must be rendering the list by some type of array or equivaletn object on server side. save both right and left side element on session.
when the list box do some element exchange. exucute your js code.
you have to update the same on server side so send the selected element index and side information to server side using ajax.
update the server side list objects in the session accordingly. Update db if needed.
From next time render this list box suing this objects on ths server side sessions.
Hope this helps.
After many years of successfully maintaining an applet that uses the good old:
<script src="foo.js"></script>
method of embedding a Java applet, we're unable to cover our ears and sing "La la la!" anymore.
It's time to be using:
deployJava.runApplet()
When I fire this method using a click handler (here using an event listener on a button via jQuery, but it doesn't matter):
$('#button').click(function() {
deployJava.runApplet(attributes, parameters, version);
});
...it wipes out the entire existing document and replaces it with the applet. All I need to know is how to target a specific DOM element to be the container for the applet, so that my page doesn't get wiped.
It seems like it would be an attribute I could pass in the form of target: someElement where "someElement" is either a DOM object or the element's ID as a string. But alas, I can't find documentation for such an attribute.
For the sake of being complete, here's what's being passed:
/*here is where I imagine there might be an applicable attribute */
var attributes = {
name: "SomeName",
code: "some.class",
archive: "some.jar",
width: 640,
height: 400
};
var parameters = {
someParameter: someValue
};
var version = "1.5";
I can document.write everything I need to rebuild a document, but I'm sure you can all well imagine how hideous that prospect seems to me.
Any pointers would be greatly appreciated.
As alternative to Christophe Roussy solution you may override document.write while running deployJava.runApplet.
Like so:
function docWriteWrapper(func) {
var writeTo = document.createElement('del'),
oldwrite = document.write,
content = '';
writeTo.id = "me";
document.write = function(text) {
content += text;
}
func();
writeTo.innerHTML += content;
document.write = oldwrite;
document.body.appendChild(writeTo);
}
An then:
docWriteWrapper(function () {
deployJava.runApplet(attributes, parameters, "1.6");
});
A little bit hackish but works like a charm;)
So the core of the problem is this: deployJava.js uses document.write. If you use this method AFTER page render (vs. as a part of the initial page render) it will first clear the document. Which has obvious negative repurcussions.
Although intended for JavaFX, people have reported success with dtjava.js, and I have every reason to believe it's a viable alternative.
However, other stakeholders on my team have already done work surrounding deployJava.js and are unwilling to throw away that work, which meant I needed to stick to deployJava.js. There's only one way to do this: make sure that deployJava is called during page render, not via Ajax, event, or other delayed trigger.
In the end, we are collecting our information, and passing it to a second page which will render the applet as expected. It works, and in most scenarios our clients will be doing this anyhow (collecting information, passing it server-side, and getting a redirect response), so it didn't make sense to force the issue. We are passing information via query string but you could probably use cookies and/or localstorage API instead, if you wanted the window.location to stay cleaner-looking.
Thanks for the replies, even though they were in the comment area. Other replies are still being taken on board if someone has a better way of doing it!
If you are using jQuery and want to target a specific dom element, rather than just appending:
function docWriteWrapper(jq, func) {
var oldwrite = document.write, content = '';
document.write = function(text) {
content += text;
}
func();
document.write = oldwrite;
jq.html(content);
}
docWriteWrapper($('#mydiv'), function () {
deployJava.runApplet(attributes, parameters, version);
});
To solve this annoying issue I downloaded and hacked deployJava.js at line 316, replaced the line by my own:
// document.write(n + "\n" + p + "\n" + r);
myDiv.append(n + "\n" + p + "\n" + r);
Where myDiv is a js global variable set to the desired div before calling runApplet:
myDiv = jQuery('#someDiv');
If you find a less intrusive solution let me know...
I am using HtmlUnit 2.10. I am creating a small link validator for a website. For crawling I am using this. during my research I was trying to crawl : loans.xxxxxxx.com. It has 58 anchor tag and 5 link tags.
I am writing a code like this
List<HtmlElement> elementsOfPage = (List<HtmlElement>) htmlPage.getElementsByTagName("link");
Iterator<HtmlElement> it = elementsOfPage.iterator();
System.out.println(elementsOfPage.size());
while(it.hasNext()) {
HtmlElement htmlElement = it.next();
System.out.println(htmlElement.toString());
}
I am also doing the same procedure for anchor tag i.e. a. For link it is just showing 3 and for anchor it is just showing 56 even though there are 5 and 58 respectively.
There are some portions in the code which are commented, I thought the web client ignores it, but if you actually print it will show some results actually are from commented code.
// Before running webclient, I have disabled applets,css, javascripts and increased the timeout to be 7seconds.
Why is this behavior odd ?
How do you get such numbers as 58 and 5? I tried to check URL you provided with HtmlUnit 2.10 + JSoup parser. Code is (Groovy, but almost Java):
def client = new WebClient(BrowserVersion.FIREFOX_3_6)
client.setThrowExceptionOnScriptError(false);
def page = (HtmlPage)client.getPage("http://loans.bankofamerica.com/en/index.html")
def doc = Jsoup.parse(page.asXml())
println doc.select("a").size()
println doc.select("link").size()
Results are 56 and 2. But with default UserAgent
def client = new WebClient()
Results are 56 and 3! Seems server gives different markup depends on useragent string (and maybe other headers).