Can not push HTML block into the android html page - javascript

I am getting a HTML block from server and want to push it into a html page in android application.
A sample html coming from server (this is the exact output with crlf etc. printed in logcat):
<ul>
<li>217</li>
<li>214</li>
</ul>
This is how I pass the output to the application html page:
runJavaScript("setHTML('"+ html +"')");
public void runJavaScript(final String code){
webview.post(new Runnable() {
#Override
public void run() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(code, null);
}else {
webview.loadUrl("javascript:" + code);
}
}
});
}
and this is the Javascript setHTML function inside the html page which is being called from android:
function setHTML(html){
$("#result").html(html);
}
this is the error:
"Uncaught SyntaxError: Invalid or unexpected token", source:
file:///android_asset/html/en/result.html (1)
I have tried debugging the project by replacing the HTML block with a simple word and it works. I think HTML characters like quotation or crlf may produce the error but I don't want to escape them (I dont want to set pure text but real html). How should I change current codes? thanks.

I guess, it's too late and doesn't answer your question exactly, as you don't want to escape any characters (I'm not sure why though), but maybe it will help somebody.
In my case, before running
runJavaScript("setHTML('"+ html +"')");
I had to escape all single quotation marks and it was enough.
html = html.replace("'", "\\'");

Related

Google Map API inside a xhtml jsf page [duplicate]

I have Google checkout sandbox generated HTML code which works fine in HTML page. When I put the same code in XHTML page, it throws the below exception:
the reference to entity "w" must end with the ';' delimiter
It's referring the request parameter w in the URL in the below src attribute:
<input type="image" name="Google Checkout" alt="Fast checkout through Google"
src="http://sandbox.google.com/checkout/buttons/checkout.gif?merchant_id=211512493599623&w=180&h=46&style=white&variant=text&loc=en_US"
height="46" width="180" />
How is this caused and how can I solve it?
The ampersand & is a special character in HTML and XML. If you want to use it as a normal character, you have to encode it correctly. Write & instead of &:
src="...9623&w=180&h=46&style=white&variant=text&loc=en_US"
& denotes the start of an encoded entity, such as < for <, or & for &. In your case the parser tries to interpret &w as an entity. But entities are always terminated by an ;, thus if the ; is missing you get the error message.
This worked on my side, when using search iq's installation code on my Blogger blog's HTML file:
<script type="text/javascript">
(function () {
window.siqConfig = {
engineKey: "6e14b3aacb2b93b658f8729adec0c030",
forceLoadSettings: false // change false to true if search box on your site is adding dynamically
};
window.siqConfig.baseUrl = "//pub.searchiq.co/";
var script = document.createElement("SCRIPT");
script.src = window.siqConfig.baseUrl + '/js/container/siq-container-2.js?cb=' + (Math.floor(Math.random()*999999)) + '&engineKey=' + siqConfig.engineKey;
script.id = "siq-container";
document.getElementsByTagName("HEAD")[0].appendChild(script);
})();
Gave me error here: &engineKey, after adding &amp replacing the & I was able to save my HTML file.

How to have functionality of Compiler in my jsp pages

I have a textarea through which user will write his code and when he press submit button then text should get compiled and result should be displayed.
Can anyone provide any API's available which I can use.?
More Details:
I have a form consisting of textarea where user can write code and submit.
On submit I want to compile this code through jsp page and return output message of compiler.
One more thing I do not Have file of submitted code, I have only string.
string code = request.getparameter("textareaCode");
So, is there any way to compile this code for any one languages ex. C, C++ or Java?
Is there any API's available which I can use to work it?
How to give system call through jsp pages so that I can compile the submitted code?
You can make use of run-time java compilation feature provided in JavaCompiler interface which accepts input/output stream.
Step 1. Convert contents submitted by text-area into input stream.
Step 2. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Step 3. Call compiler.run method by providing inputstream(you have created in step 1) as one argument. You can capture the output of compilation thru output stream as another argument.
You can execute command line commands using Runtime.getRuntime().exec("command");
For example if you want to compile a java file then try the following :
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// Logic to save textarea code into java file.
// then compile a java file "javac fileName.java" command
// using the Runtime exec method
Process p = Runtime.getRuntime().exec("javac fileName.java");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}

Adding a script element to an existing TWebBrowser document

Prompted by a couple of SO qs this weekend, I decided to see if I could work out how
to add some javascript in an Html element to a document loaded in a TWebBrowser. Doing so,
I've run into an oddity which maybe someone can explain.
Here's my Html document
<html>
<body>
Something
<br>
<div id="forscript">some more text</div>
</body>
</html>
and my javascript element I want to add to it
<script type="text/javascript" defer="false">{alert('hello');}</script>
which I pass as the Script argument to AddScript() below.
This is my code (doc2 is an IHtmlDocument2 obtained from the WebBrowser):
procedure TForm1.AddScript(const Script : String);
var
Element : IHtmlElement;
Doc3 : IHtmlDocument3;
begin
Doc2.QueryInterface(IHtmlDocument3, Doc3);
Element := Doc3.GetElementByID('forscript');
Element.innerHTML := Element.innerHTML + Script;
end;
This works fine, but ...
The reason for the Element.innerHTML on the RHS of the assignment is simply that I found that
if the RHS contains only the Script js, the js does't execute. My question is, why not, and is there a simpler alternative, like somehow creating an IHtmlScriptElement in code and inserting it in the DOM? Obviously my simple-minded work-around is simply to prepend the text the
Element already contains, but I have a slightly hard time believing that people who actually know what they're doing would find that necessary.
FWIW #1: I tried using Element.insertAdjacentHtml to add the script but got the same behaviour as I've just described, in terms of needing to insert something in addition to the script to get the script to be executed, so I'm wondering whether it's something to do with how the DOM is processed after a change is made to it.
FWIW #2: I've used the Element.innerHtml route because TWebBrowser/MSHTML.Pas have resisted my
attempts to create an IHtmlScriptElement in code; AFAICS, attempting to use any of the
CohtmlXXXElement routines in MSHTML.Pas provoke a "Class not registered" exception, which seems to confirm a comment I came across somewhere by #kobik of this parish.
(Btw, using D7 + IE11 on Win7 64-bit)
Here' a complete example how to use IHtmlScriptElement.
Html is loaded at application startup.
The code under Button1Click adds the javascript to the DOM and executes it:
unit u_frm_SO27091639;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OleCtrls, SHDocVw, MsHtml, ActiveX;
type
TForm1 = class(TForm)
WebBrowser1: TWebBrowser;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure LoadDocFromString(Webbrowser : TWebbrowser);
var
Strm : TStringStream;
Adapter : TStreamAdapter;
begin
WebBrowser.Navigate('about:blank');
// warning - don't use this trick in production code, use the `OnDocumentComplete` event
while WebBrowser.ReadyState <> READYSTATE_INTERACTIVE do
Application.ProcessMessages;
// end of warning
Strm := TStringStream.Create;
try
Strm.WriteString('<html><body>Something<br></body></html>');
Strm.Seek(0, 0);
Adapter := TStreamAdapter.Create(Strm);
(WebBrowser.Document as IPersistStreamInit).Load(Adapter) ;
finally
Strm.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Doc2 : IHtmlDocument2;
Script : IHtmlDOMNode;
HTMLWindow: IHTMLWindow2;
begin
Doc2 := Webbrowser1.Document as IHtmlDocument2;
if Assigned(Doc2.body) then
begin
Script := Doc2.createElement('script') as IHTMLDOMNode;
(Script as IHTMLScriptElement).text := 'function helloWorld() { alert("hello world!") }';
(Doc2.body as IHtmlDomNode).appendChild(Script);
HTMLWindow := Doc2.parentWindow;
if Assigned(HTMLWindow) then
HTMLWindow.execScript('helloWorld()', 'JavaScript')
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
LoadDocFromString(Webbrowser1);
end;
end.

Eclipse, JavaScript, UTF-8, and tabs (on a mac)

I ran a few javascript files thru my spaces2tabs converter (ps I was porting to coffeescript which is why I needed tabs - have since abandoned coffeescript)
public static String convertSpacesToTabs(String str, int spacesPerTab) {
assert (spacesPerTab >= 1);
StringBuilder builder = new StringBuilder();
for (int i = 0; i = 0) {
//System.out.println("old: " + oldIdx + " new: " + newIdx);
sb.append(str.substring(oldIdx, newIdx));
sb.append('\t');
oldIdx = newIdx + toFind.length();
newIdx = str.indexOf(toFind, oldIdx);
}
sb.append(str.substring(oldIdx, str.length()));
return sb.toString();
}
Worked like a charm: replaced spaces with tabs. Looks perfect in TextMate, runs fine, etc etc. Perfectly valid UTF-8
The ONLY issue comes up in eclipse, where it is a mess.
It seems like eclipse cannot deal with the \t's I inserted. When initially opening the files, eclipse shows a strange character and flags these tabs with the message "Invalid Character" delete this token. When I go to the project properties under Resource I changed text version to utf-8 and the strange characters go away, but the error message doesn't!
Is there an easy way to make eclipse happy?
Seems like a bug in eclipse... no fix as far as I'm aware...

Android Inject in webview external js, execute function, and raise an alert

I want to inject an external javascript in webview and execute one of its functions execute(). After completion an alert is raised and the string returns to the activity
this is how I do it but it doesn't seem to work (the js is already tested)
view.loadUrl("javascript:(function() { var script=document.createElement('script');script.type='text/javascript';script.src=" + jsFileURL + ";" + "document.getElementsByTagName('head').item(0).appendChild(script);window.HTMLOUT.showHTML(execute());})()");
this is how I implement HTMLOUT, while the alert is overrided in ChromeClient
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); browser.setWebViewClient(new mWebViewClient()); browser.setWebChromeClient(new mChromeClient()); browser.loadUrl("file:///android_asset/Travian comx2b.htm");
Ok after many many attempts I found a workaround, but unfortunately not the "solution". I used this load view.loadUrl("javascript:" + src + " execute(); " + ""); while the source src comes from a text file script.js which includes my javascript (both functions and plain commands)
//get script
InputStream is;
String src= "";
try {
is = getAssets().open("travianbot.js");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
src = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a sample of the script.js (be careful on line endings ";")
function addItem(v, link, x, y, result) {
//function commands
}
function popup() {
alert(execute().split("#"));
}
function execute(){
//function commands
additem(...);
}
// plain commands
.......
One resolution for a remote script, which I haven't tested it, is to parse the remote script (e.g. as inputstream) and then included it as plain text.
I think u have to enclose the jsFileUrl in single quotes.
script.src='" + jsFileURL + "';"
please check out this http://lexandera.com/2009/01/adding-alert-support-to-a-webview/
Thanks

Categories

Resources