Windows.Forms.WebBrowser loading page with local SVG file - javascript

I have an HTML page that generating in C# project. it works, when I open this page in IE.
<!DOCTYPE HTML>
<meta http-equiv='X-UA-Compatible' content='IE=10' />
<html lang='en'>
<head>
<title>TemplateSVG</title>
<script type='text/javascript' src='InterfaceSVG.js'></script>
</head>
<body style='margin: 0; overflow: hidden;'>
<div class="page-content">
<object id='idSVG' type='image/svg+xml' data='D:\Examples\ExampleFla.svg'></object>
</div>
</body>
</html>
I loaded getting text in Web browser
if (webBrowser.Document == null)
{
webBrowser.DocumentText = theHTMLtext;
}
else
{
webBrowser.Document.OpenNew(true);
webBrowser.DocumentText = theHTMLtext;
}
But file InterfaceSVG.js isn't find.
When I give full Path to js file src='D:\[Path]\InterfaceSVG.js'
JS script generate exception on line with getSVGDocument().
var SvgDoc;
window.addEventListener('load', function () {
SvgDoc = document.getElementById("idSVG");
if (SvgDoc == null) { alert("error"); return; }
SvgDoc = SvgDoc.getSVGDocument(); // IE created Access Deny.
});
Edit:
Try to insert text from js file.
<script>Text from InterfaceSVG.js </scipt>
But it generates the same exception (Access Deny) on line with getSVGDocument()
I saved result HTML page in a folder with SVG file and use function Navigateinstead of DocumentText. Now it works... but I don't want to write on disk anything.
string path = Path.GetDirectoryName(pathToSvgFile);
string file = "\\"+Path.GetFileNameWithoutExtension(pathToSvgFile);
string newfile = path + file;
File.WriteAllText(newfile, theHTMLtext);
webBrowser.Navigate(newfile);

I found how need to open a user Page.
Create template HTML page without scripts.
<!DOCTYPE HTML>
<meta http-equiv='X-UA-Compatible' content='IE=10' />
<html lang='en'>
<head>
<title>Empty Page</title>
</head>
<body style='margin: 0; overflow: hidden; '>
<div class="page-content">
<object id='idSVG' style='height: 100%; width: 100%; position:absolute;' type='image/svg+xml' data='{0}'></object>
</div>
</body>
</html>
Add script files and change text body of HTML page what you need in event webBrowser.Navigated.
static string PathToSvgFile;
public static void OpenSVG(this WebBrowser webBrowser, string pathToSvgFile)
{
if (webBrowser.ReadyState == WebBrowserReadyState.Complete || webBrowser.ReadyState == WebBrowserReadyState.Uninitialized)
{
webBrowser.Navigate([Path to emptyPage.html]);
PathToSvgFile = pathToSvgFile;
webBrowser.Navigated += webBrowser_Navigated;
}
}
private static void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
var webBrowser = ((WebBrowser)sender);
HtmlElementCollection head = webBrowser.Document.GetElementsByTagName("head");
if (head != null)
{
var element = webBrowser.Document.CreateElement("script");
element.SetAttribute("type", "text/javascript");
var elementDom = (MSHTML.IHTMLScriptElement)element.DomElement;
elementDom.src = [JavaScriptFile.js];
((HtmlElement)head[0]).AppendChild(element);
}
webBrowser.Document.Body.InnerHtml = String.Format(webBrowser.Document.Body.InnerHtml, PathToSvgFile);
webBrowser.Navigated -= webBrowser_Navigated;
}

Related

On changing script attribute value dynamically, reloads html with appending new script replacing previous one

I want to change its script in the head section of the HTML dynamically on clicking the button and want to reload the page with a new script(with its new values) replacing previous one with JavaScript.
/* To change the root api */
function passRoot(data) {
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.head.appendChild(newScript);
window.location.reload();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script id="someID" api-root="some-api-value" data-root="some-data-value" src="some-src-value"></script>
</head>
<body>
script change:
<textarea style="font-size: 9px; width: 90%; height: 30%" id="passroot">
{"api-root": "enter new value", "data-root": "enter new value", "src":"some-new-src-value"}</textarea
>
<div>
<button onclick="passRoot(document.querySelector('#passroot').value)">
Submit to change script
</button>
</div>
**************html-starts***********************************<br>
stuff I manage with bundle, here I want to load new bundle after providing new url in the src of script tag
</body>
</html>
Please open view frame source in the code snippet to see the script tag.
Please help!
Why you want to change the script tag. If you want to load your js on some event. Let's say button click. Please go for Dynamic import that will run your script file.
When you reload the page the script will be removed. So you need to use localStorage to keep current script attribute:
let scriptData = localStorage.getItem('script');
if (scriptData)
craeteScript(scriptData);
function craeteScript(data) {
localStorage.setItem('script', data)
const parsedData = JSON.parse(data);
var newScript = document.createElement("script");
newScript.id = "someID";
newScript.setAttribute("data-root", parsedData["data-root"]);
newScript.setAttribute("api-root", parsedData["api-root"]);
newScript.setAttribute("src", parsedData["src"]);
document.body.appendChild(newScript);
}
function passRoot(data) {
craeteScript(data);
window.location.reload();
}

Android web view load javascript in random order / not loading

I have an issue with a web view I'm using.
The javascript files used to render the view properly MUST be loaded in a specific order.
On browser (chrome mobile; safari desktop, ...) it works well.
However in my web view the result is unpredictable.
This is one of the latests failing run I had:
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<script src="js/script3.js"></script>
<script src="js/script4.js"></script>
... More scripts...
</body>
</html>
Here is the Java code:
mWebView = (WebView)findViewById(R.id.webView);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setHorizontalFadingEdgeEnabled(false);
mWebView.setScrollbarFadingEnabled(false);
mWebView.setVerticalFadingEdgeEnabled(false);
mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
mWebView.loadUrl("http://192.168.1.24:8000/path/to/index.html");
The issue is that randomly, javascript files are interpreted in wrong order or just not loaded.
From my understanding, javascript MUST be loaded in declaration order.
Am I wrong ?
Is there anything I can do to change that behavior ? (other than concatenating all JS together..)
Your scripts will work on the web site but for make it work on the android you need to load the scripts manually. See the function how it load the script from assets.
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
See Here Example
also make sure you enabled JS:
webSettings.setJavaScriptEnabled(true);
and the manifest ofcourse:
<uses-permission android:name="android.permission.INTERNET" />

Pop-up based on location (Specifically the UK)

I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>

grid 960 - while executing inspectSection in dmx960 grid, js error occurred.

I'm trying to run this grid extention in DW CS5. I'm a front end person so debugging other people's code isn't my thing. So when I try set the grid precepts I get this error:
while executing inspectSection in dmx960 grid, js error occurred.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Barefoot Development Group</title>
<link href="CSS/Style.css" rel="stylesheet" type="text/css">
<link href="CSS/text.css" rel="stylesheet" type="text/css">
<link href="CSS/reset.css" rel="stylesheet" type="text/css">
</head>
<body>
<!------start container------->
<div id = "container" class ="container_16"></div>
<div id = "social_search" class = "grid_16"></div>
<div id = "social_links" class = "grid_1 alpha"></div>
<!------Main container-------->
<!------Header start---------->
<!------Social Links---------->
<!-------End social links------>
<!----start Social icons -------->
<!----end social icons----->
</body>
</html>
I tried deleting the cache in Config folder and reinstalling the extension. Didn't work. I checked the log files and found this:
JS Error: theElem.getAttribute is not a function filename:
C:\Users\cvr\AppData\Roaming\Adobe\Dreamweaver
CS5\en_US\Configuration\Shared\DMXzone\960 Grid\dmx960grid_lib.js
lineno: 598
So I went to the JS file and here is what I found in this expression block:
function getGridClassNum(theElem) {
if (!theElem) return 0;
var cls = theElem.getAttribute("class");
if (!cls) return 0;
if (cls == 'clearfix') {
//Try to read the parent
var parent = getGridElement(theElem.parentNode);
if (parent && parent.nodeType === Node.ELEMENT_NODE) {
return getGridClassNum(parent);
}
} else {
var numMatch = cls.match(new RegExp("\\b(grid|container)_(\\d+)\\b"));
if (numMatch && numMatch.length > 1) {
return parseFloat(numMatch[2]);
// //decrease with prefix and suffix
// - getGridClassNameNum(theElem, 'prefix')
// - getGridClassNameNum(theElem, 'suffix');
}
}
return 0;
}
I don't see anything particularly amiss here. But perhaps a more expert debugger can tell me if there is something going on here. Here is what confuses me - I was looking for the function inspectSection but I couldn't find it. I'm left scratching my head here.
Could this be a problem of including the script directly into the html doc?
Thanks!

Upload image not showing on IE9 - error SCRIPT438: Object doesn't support property or method

My client has problem with website only in IE9 (the page works fine in Firefox and Chrome):
The website has an upload form in pop-up window. After processing, the pop-up window is closed and uploaded file (image) is shown in main (top, "father") page.
The code of pop-up is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>..:: Upload Img ::..</title>
<link href="/css/admin.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">
function fcnReload() {
top.showFotos('127d4efeef19abfcbc411507bd9d5de6', '_cookie.jpg|_f0.jpg');
}
</script>
</head>
<body onunload="fcnReload();">
<h3>Image uploaded - OK</h3>
Close the window<br /><br />
</body>
</html>
For some reasons, uploaded image not showing on IE9 and there is error:
SCRIPT438: Object doesn't support property or method 'showFotos' 1.html, line 9 character 6.
Probably there is some kind of IE problems on updating parent window: link1, link2
The function showFotos code:
function showFotos(session, names) {
var arrNames = names.split('|');
strNames = '';
for (var i=0; i<mdl_fotos; i++) {
if ((i==0) && (sel_mod==11)) {
document.getElementById('Preview-Color').src = '/uploads/'+session+arrNames[i+1];
document.getElementById('Preview-Color').style.width = '444px';
document.getElementById('Preview-Color').style.height = '350px';
strNames += ','+arrNames[i+1].replace('_','');
} else {
document.getElementById('ExtImg'+(i+1)).src = '/uploads/'+session+arrNames[i+1];
strNames += ','+arrNames[i+1].replace('_','');
}
}
if (arrNames[0] != '')
document.getElementById('Preview-Cookie').src = '/uploads/'+session+arrNames[0];
strSession = session;
strNames = arrNames[0].replace('_','')+strNames;
}

Categories

Resources