How can I load a local script using VB.Net WebView control? - javascript

I develop an application that use a WebView in a WinForm using VB.NET.
The HTML code displayed in WebView is dynamically generated using VB.NET code.
wvSelect.Settings.IsScriptNotifyAllowed = True
wvSelect.Settings.IsJavaScriptEnabled = True
wvSelect.NavigateToString(sHtmlText)
where sHtmlText contains HTML tags and values.
This work well.
My HTML string is generated in a module
Public eHtml =
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
// script (see code below)
</script>
<style type="text/css">
That's working, but Javascript code crash every time I write a < characters and color formatting of Javascript code is not optimal.
I know that I can use
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
That works for < and > characters but color formatting is very bad.
So, I have decided to move all my Javascript code in .JS file.
My HTML now, look like this
Public eHtml =
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="file:///D:/Documents/app.js"></script>
<style type="text/css">
Since, I have made this change, what is displayed in WebView is different from what I obtained before !
I suppose that .JS file is not called, not found or something else.
You must know that just before loading HTML string in WebView, I save it in an .HTML file.
When I double click on this .HTML file, Chrome load it and what is displayed is correct.
The problem happens only when HTML string is displayed on WebView.
As you can see, I don't have any problem importing JQuery script.
This problem is only for LOCAL scripts.
For information, my Javascript file contains following lines (I have removed some lines)
It is just to show that JQuery is used.
var eUnicode;
var iCounter = 0;
var eDraggable;
$(document).ready(function () {
$('.button').attr('draggable', 'True');
$('.digit').click(function (ev) { clickDigit(ev); });
$(".button").click(function (ev) {
clickButton(ev.target);
});
showFirstTab();
});
function clickButton(eButton) {
var sName = event.srcElement.innerText;
hideAllOnglets();
eButton.style.background = "orange";
showOnglet(sName);
}
function showTab(sName) {
var eOnglet = document.getElementById(sName);
eOnglet.style.display = "block";
}
Has somebody already encountered and resolved this problem ?

I have solved my problem using an embedded file (VB.Net Resource).
This technic is more safe because embedded file in not modifiable by user on installation location.
The Javascript.js file is located my application file/folder tree and has been defined as embedded resource in Build Action property as explained on How do I include a .jpg into a dll?
.
I don't use <script src='location'> tag because it don't work and also because HTML string is already dynamically build from my code for other part.
My VB.Net code is following
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
sHtmlText = eHtml.ToString()
sHtmlText = sHtmlText.Replace("(%-ONGLET-%)", sOngletText)
sHtmlText = sHtmlText.Replace("(%-TABLE-%)", sTableText)
reader = New StreamReader(ass.GetManifestResourceStream("UnicodeInput.JavaScript.js"))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
sHtmlText = sHtmlText.Replace("(%-SCRIPT-%)", sScriptText)
reader = New StreamReader(ass.GetManifestResourceStream("UnicodeInput.StyleSheet.css"))
Dim sStyleText = reader.ReadToEnd()
reader.Close()
sHtmlText = sHtmlText.Replace("(%-STYLE-%)", sStyleText)
wvSelect.Settings.IsScriptNotifyAllowed = True
wvSelect.Settings.IsJavaScriptEnabled = True
wvSelect.NavigateToString(sHtmlText)
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("output.html", False)
file.Write(sHtmlText)
file.Close()
As you can see I have done same improvement for CSS file and I have discovered that this file has some errors !
My 'pseudo' HTML code is following
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!--
<script type="text/javascript" src="./app.js"></script>
<script type="text/javascript" src="file:///D:/Documents/+Informatique/Application/#Visual Basic.NET/UnicodeInput/app.js"></script>
<script src="file:///D:/Documents/app.js"></script>
-->
<script type="text/javascript">
(%-SCRIPT-%)
</script>
<style type="text/css">
(%-STYLE-%)
</style>
</head>
<body>
<div id="onglet">
<div class='button'>Keyboard</div>
(%-ONGLET-%)
<div class='button' onclick="GetNewCmdFile()">*ADD</div>
</div>
What is in comment is what I have already tried that doesn't work in WinForm VB.Net WebView but works perfectly in pure HTML on Chrome.

Related

How to regex replace from a showdown extension in js?

I am making a markdown (showdown js) extension for mathematics, expressions and plotting graphs. however I faced a problem here.
I cannot replace a pattern by regex in the extension code, but I can replace it with the replace method!
what I've tried:
//load showdown module
// https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0
// i don't know how to load from js, i loaded from <script src="...">
// we replace {graph:<expression} into a div of class graph
function mathext(){
return [{
type:"lang",
regex:/{graph:(.*)}/gi,
replace:"<div class='graph'>$1</div>"
}
];}
// load the extension
showdown.extension("mathext",mathext);
// create a converter
let converter = new showdown.Converter();
// make a function to convert markdown to html with pre-configured extension
function mathmd(md){
return converter.makeHtml(md);
}
// convert a ready markdown string to html.
let mathmds="# hello\n`x^2+y^2=9`\n##hello2\n{graph:x^2+y^2=9}";
document.getElementById("mathmd").innerText=mathmd(mathmds);
an html that runs this script looks like this:
<head>
<meta charset="utf-8">
<title>md</title>
</head>
<body>
<div id="mathmd"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0/showdown.min.js"></script>
<script src="mark.js"></script>
</body>
</html>
manual
Here is the manual replacement that correctly works:
let mathmds="# hello\n`x^2+y^2=9`\n##hello2\n{graph:x^2+y^2=9}";
let reg=/{graph:(.*)}/gi;
let toreplace="<div class='graph'>$1</div>"
alert(mathmds.replace(reg,toreplace));
Why does that happen? How to replace the pattern correctly?
Thanks in advance.

How to find where javascript starts and end in asp files?

I need to write a script in c# that recognizes javascript inside an ASP file.
I would like to start deleting all comments, but I am facing the problem: to know if a sequence of characters is a comment or not I need to know first if I am inside HTML or a script written in javascript.
Is there a (quite simple) way to recognize where the javascript code starts and ends?
Let's suppose I have this file, I need to remove the comment in javascript but not the same string in HTML, where it is not a comment:
<html>
<head>
<script type="text/javascript">
function onLoad() {
try {
if (top.location.href != location.href) {
top.location.href = "myFile.aspx";
//this is a comment
} catch (e) { }
}
</script>
</head>
<body>
<p>//this is not a comment</p>
</body>
</html>

Html code to Png image

I made a web application which allow the user to create an image dynamically in JavaScript.
It use jQuery to allow the user to place div, resize them and drag them into a <div> Container.
When the user finished to place all div, he can press the "Generate" button which send the <div> Container outerHTML code into a local database.
Then the user can use another script, in php, and past in parameter the id in the database of which render he want to display, then the php script create a page using the code in the database.
My problem is now I want to take the code of this generated html page, then convert it into a png image.
I looked at some other posts and found something interesting : Phantom.js
But what I tried doesn't seem to work. Here is my code :
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<script>
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
</script>
</body>
</html>
So we have the database with the div outerHTML code contained at the id '0'.
"affichage.php" take in parameter a variable "afficheur" then it ask the database to get the code from this variable. For example, afficheur=0 will return the div code contained in the database at the id=0.
When I go to "http://10.237.35.10/maxime/affichage.php?afficheur=0" I have a html page with the render I want. But when I try to run the script I'd posted higher, I haven't any "affichageTest.png" rendered in my folder.
What do I have to do? Do I have to import anything else to run Phantom.js? Or maybe I need to add something to my code?
PhantomJS is a binary not a javascript librarie (it is actually a headless webkit), I can not test it here atm, but here the main idea :
First download the PhantomJS binary, upload it somewhere and make it executable (chmod +x).
Create a file named test.js with this code below :
var page = require('webpage').create();
page.open('http://10.237.35.10/maxime/affichage.php?afficheur=0', function() {
page.render('affichageTest.png');
phantom.exit();
});
Create a file named display.php with this code below :
<?php
$file_path = exec('/path/to/phantomjs test.js');
?>
<html>
<head>
<title>Test</title>
<LINK rel='stylesheet' type='text/css' href='style.css'>
<script type='text/javascript' src='jquery/jquery.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
</head>
<body>
<img src="<?php $file_path ?>" alt="test">
</body>
</html>
Visit the display.php page to see the screen capture
If you need a full script solution, as you have said in comments, your only hope is Image Magic php extension. This in conjunction with HTML2PDF can be used to device html to image conversion for non-complex markup.
The trick is to create a pdf out of html first:
$html2pdf = new HTML2PDF('P', 'A4');
$html2pdf->writeHTML($html_content);
$file = $html2pdf->Output('temp.pdf','F');
Now you can get this pdf file and convert it image using Image Magic
$im = new imagick('temp.pdf');
$im->setImageFormat( "jpg" );
$img_name = time().'.jpg';
$im->setSize(800,600);
$im->writeImage($img_name);
$im->clear();
$im->destroy();
Installation of Image Magic extensions and support libraries could be painstaking. Please read the installation notes carefully.
The complexity of the html markup which could be converted is limited. You can do a fairly good job. But you can't call it a day if you need to convert ANY html.

Jsp expression language not evaluated in .js files

I am making a Java EE 6 application and using Glassfish 3.1.2.2.
I wan't to use EL inside a jquery script, stored in a sepparate .js file but I can't get it to work. This is the script:
$(document).ready(function(){
$("select#classLabel").change(function(){
var unsetList = ${classyJson};
var chosen = $("select#classLabel").val();
$("select#classSubLabel").val(chosen);
});
});
And I get the following error message from netbeans:
"subLabelSet.js: Expected ; but found {
Expected semicolon ; after 'classy'.
The global variable 'classy' is not declared."
The same script works fine if I put it directly in the .jsp file like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Titly</title>
<script type="text/javascript" src="js/jquery-1.10.2.js" ></script>
<script type="text/javascript" src="js/generateSavedSearchTable.js" ></script>
<script type="text/javascript" src="js/subLabelSet.js" ></script>
<script>
$(document).ready(function(){
$("select#classLabel").change(function(){
var unsetList = ${classyJson};
var chosen = $("select#classLabel").val();
$("select#classSubLabel").val(chosen);
});
});
</script>
</head>
This reminded me of a problem I had before where I couldn't get the EL to evaluate inside files ending in '.jspf'. This I fixed by adding:
<jsp-property-group>
<description>Used to enable interpretation of EL in jspf files</description>
<display-name>jspf</display-name>
<url-pattern>/WEB-INF/jspf/*</url-pattern>
</jsp-property-group>
in the web.xml file. But when I try to do the same for .js files:
<jsp-property-group>
<description>Used to enable interpretation of EL in javascript files</description>
<display-name>javascript</display-name>
<url-pattern>/js/*</url-pattern>
</jsp-property-group>
I does not work and I get the following error:
SEVERE: PWC6117: File "C:\S1\Documents\netbeansprojects\UI\build\web\js\generateSavedSearchTable.js" not found
SEVERE: Error compiling file: C:\S1\GlassFish_Server\glassfish\domains\domain1\generated\jsp\UI\org\apache\jsp\js\jquery_002d1_10_2_js.java
WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP
PWC6199: Generated servlet error:
code too large for try statement
PWC6199: Generated servlet error:
code too large for try statement
PWC6199: Generated servlet error:
code too large
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:129)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:299)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:392)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:724)
Any ideas on what is going wrong and if/how I can fix it?

Uncaught ReferenceError when accessing an object from another JS file

I have various JS libraries in my web application, which are loaded before my main JS file (main.js). One of these libraries is jshashtable, but when I try to create a new Hashtable object in main.js, Google Chrome and Firefox throw a ReferenceError, complaining that the variable does not exist.
Here is the <head> of the application:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="/static/jquery-1.4.4.min.js"></script>
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<script type="text/javascript" src="/static/main.js"></script>
Here is the problem line in main.js:
posts = new Hashtable();
This line is inside a function called init which is called when the page has finished loading (using the jquery $(document).ready() function).
Any reason why Hashtable is not global? Google maps and jquery objects work with no such problem. The source of jshashtable can be seen on Google code.
Updated answer: The problem is that you've got a typo in the script tag:
<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<!-- ^^---- here (the letters are transposed) -->
I couldn't understand why you would be running into a problem and decided to actually copy-and-paste your script tags and replicate the structure exactly on my machine. And things stopped working and my world tilted 3° counter-clockwise until I finally stared at them long enough to see it.
Provided that the jshashtable code really is at /static/jshashtable-2.1.js and your server is serving it up correctly (double-check on Chrome's resources tab in the dev tools), I can't see any reason for that. Your scripts are in the right order, and jshashtable's docs show using a global Hashtable (and the code link you gave clearly shows it creating one).
Edit: I've just replicated that same structure (same scripts, same order, using jQuery(document).ready(function() { ... });) on my own server, and am not having that problem. I can create a Hashtable and use its functions.
My HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type='text/javascript' src='jquery-1.4.4.js'></script>
<script type='text/javascript' src='jshashtable-2.1.js'></script>
<script type='text/javascript' src='main.js'></script>
</head>
<body>
</body>
</html>
My main.js:
jQuery(document).ready(function() {
try {
var ht = new Hashtable();
display("typeof ht = " + typeof ht);
display("ht.size() = " + ht.size());
}
catch (e) {
display("Exception: " + e);
}
function display(msg)
{
$("<p>").html(msg).appendTo(document.body);
}
});
Only difference is I'm not using a /static prefix, and I'm absolutely certain that makes no difference.

Categories