I need some javascript code to read a "markdown file" from my http directory and place it into a javascript string. How would I modify this code to do that?
<!-- FILE: index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Markdown TexDollar Reader</title>
<!-- Javascript setup using node.js: ->
<!-- C:\demo> npm install mathjax -->
<!-- C:\demo> npm install showdown -->
<script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
});
</script>
<script type="text/javascript"
src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
</head>
<body>
<script>
converter = new showdown.Converter();
<!-- FIXME: Instead of setting text string manually from javascript,
i want to load my file
in http directory called "markdown.md" into the javascript string text-->
text = '# hello, markdown!';
text += '\nthis is a test';
text += '\n$$e=mc^2$$';
html = converter.makeHtml(text);
document.write(html);
</script>
</body>
</html>
The only way to load a text file locally without an http server is to use the HTML5 api for loading a file through a file dialog where the use selects a markdown file to read:
<!DOCTYPE html>
<html>
<head>
<title>Render "Markdown file with Tex-Dollar" in browser</title>
<!-- node.js packages required: -->
<!-- npm install jquery -->
<!-- npm install showdown -->
<!-- npm install mathjax -->
<script type="text/javascript" src="./node_modules/showdown/dist/jquery.js"></script>
<script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
});
</script>
<script type="text/javascript"
src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
<script type="text/javascript">
var reader;
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
function displayContents(txt) {
converter = new showdown.Converter();
html = converter.makeHtml(txt);
var el = document.getElementById('main');
el.innerHTML = html; //display output in DOM
MathJax.Hub.Queue(["Typeset",MathJax.Hub, "main"]);
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
The mathjax rendering is a little flaky when loading from markdown... if anybody knows how to fix it. let me know. thanks.
Related
I like to add Media.Net Network via JavaScript to MoPub. The team from Media.Net send me javascript I shoudl add to MoPub Network tab. So far so good.
They send me exactly this code:
//Add this code in head section
<script type="text/javascript">
window._mNHandle = window._mNHandle || {};
window._mNHandle.queue = window._mNHandle.queue || [];
medianet_versionId = "3121199";
</script>
<script src="//contextual.media.net/dmedianet.js?cid=MYCUSTOMERKEY" async="async"></script>
//Add this code in body section
<div id="BANNERKEY">
<script type="text/javascript">
try {
window._mNHandle.queue.push(function () {
window._mNDetails.loadTag("BANNERKEY", "320x50", "BANNERKEY");
});
}
catch (error) {
}
</script>
</div>
I believe both tags should go to the network tab of MoPub like this:
But here comes the question. MoPub highly recommends to add a failover tag in case the network responds with a no fill or any other error. But my knowledge is limited to add this failover tag to the Media.Net javascript code.
<script type="text/javascript" charset="utf-8"> loaded=true; window.location="mopub://failLoad"; </script>
I added the failover tag to the catch block and it seems to work.
<script type="text/javascript">
window._mNHandle = window._mNHandle || {};
window._mNHandle.queue = window._mNHandle.queue || [];
medianet_versionId = "3121199";
</script>
<script src="//contextual.media.net/dmedianet.js?cid=MYCUSTOMERKEY" async="async">
</script>
<div id="BANNERKEY">
<script type="text/javascript">
try {
window._mNHandle.queue.push(function () {
window._mNDetails.loadTag("BANNERKEY", "320x50", "BANNERKEY");
});
}
catch (error) {
loaded= true;
window.location="mopub://failLoad";
}
</script>
</div>
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;
}
I have hdf5 file created using c++ application.i want to read the same hdf5 file inside browser using javascript.
Hdf5 file will be download from server using xhr or web socket request and the content of the file will be stored in javascript variable then i want to read the content of the variable.
Please tell me any javascript library available to read the hdf5 inside browser.
i tried "https://github.com/HDF-NI/hdf5.node" but it supports only for nodejs.
Is it possible to convert the above library to support reading inside browser.
It is only able to read a subset of HDF5 files, but this is something that works:
https://github.com/usnistgov/jsfive
It basically covers all the files that can be read by the pyfive library (https://github.com/jjhelmus/pyfive), as it is a direct port of that library.
The best two libraries that I found are jsfive and h5wasm:
Sample code jsfive:
$(document).ready(function() {
$("#datafile").change(async function loadData() {
var file_input = $("#datafile")[0];
var file = file_input.files[0]; // only one file allowed
let datafilename = file.name;
let reader = new FileReader();
reader.onloadend = function(evt) {
let barr = evt.target.result;
var f = new hdf5.File(barr, datafilename);
let value = f.get('main').value
let attrs = f.get('main').attrs
// do somthing with f
}
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import JSFive -->
<script src="https://cdn.jsdelivr.net/npm/jsfive#0.3.7/dist/hdf5.js">
<!-- Import main JS -->
<
script src = "app.js" >
</script>
</body>
</html>
Sample code h5wasm:
import * as hdf5 from "https://cdn.jsdelivr.net/npm/h5wasm#latest/dist/esm/hdf5_hl.js";
await hdf5.ready;
$(document).ready(function() {
$("#datafile").change(async function loadData() {
let file = $("#datafile")[0].files[0];
let data_filename = file.name;
let ab = await file.arrayBuffer();
hdf5.FS.writeFile(data_filename, new Uint8Array(ab));
let f = new hdf5.File(data_filename, "r");
// do somthing with f
f.close()
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import main JS -->
<script type="module" src="app.js" ></script>
</body>
</html>
Also interesting jsfive with callback:
function storeTarget(result, file_name) {
f = new hdf5.File(result, file_name);
}
$("#datafile").change(async function loadSource() {
var file_input = $("#datafile")[0];
var file = file_input.files[0];
let datafilename = file.name;
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => storeTarget(reader.result, datafilename);
})
I want to create a simple script that changes LESS variables and print the CSS output in a div.
this is my HTML
<input type="text" id="choose-color" onchange="ModifyColorsInLess()">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
This is my js
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status === 200 && xmlhttp.readyState === 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","css/styles.less",true);
xmlhttp.send();
}
function ModifyColorsInLess() {
less.modifyVars(
{
'#colore-body': $("#choose-color").val()
}
);
}
The script prints CSS code correctly, but if i insert a new color value in the input type="text" and call the writeCSS function, it doesn't print my variable edit.
I think the problem is that "modifyvar" does not change the file "styles.less", so when I call the function writeCSS() does not detect changes made.
is there a way to print the css dynamically detecting changes made with modifyvar?
update
When you allow the compiled styles are directly applied on your page, you can simply call `modifyVars as follows:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<link rel="stylesheet/less" type="text/css" href="t.less">
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
less.modifyVars({
'colore-body': document.getElementById('choose-color').value
});
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
Demo: http://plnkr.co/14MIt4gGCrMyXjgwCsoc
end update
Based on How to show the compiled css from a .less file in the browser?, How to update variables in .less file dynamically using AngularJS and Less: Passing option when using programmatically (via API) (you should also read: http://lesscss.org/usage/#programmatic-usage) you should be able to use the code like that shown below:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var options = {}
options['modifyVars'] = {'colore-body' : document.getElementById('choose-color').value}
lessCode = xmlhttp.responseText;
less.render(lessCode, options, function (error, output) {
if(!error) {
document.getElementById('lesscode').innerHTML = output.css;
}
else document.getElementById('lesscode').innerHTML = '<span style="color:red">' + error + '</span>';
});
}
};
xmlhttp.open("GET","styles.less",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
demo: http://plnkr.co/YbdtOwOeQPC1k9Vq4ZBv
And finally based on Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload you can prevent caching of your source file with the following code:
xmlhttp.open("GET","t.less?_=" + new Date().getTime(),true);
In the above the env: "development" setting prevents your source files from caching. To clear the cache otherwise, you should call less.refresh(true) before your less.render call.
i have another little problem, if in my less file there is a reference
to another less file like this(#import "another.less") script doesn't
work.
Make sure that another.less in the above is in the same folder as your styles.less file. Notice that import (when using less in browser) are read with a XMLHttpRequest too. So your imported files should be readable by browser and their paths should be relative to the styles.less file. Also see http://lesscss.org/usage/#using-less-in-the-browser-relativeurls
The recommendation of the open source web analysis software Piwik is to put the following code at the end of the pages you want to track, directly before the closing </body> tag:
<html>
<head>
[...]
</head>
<body>
[...]
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://piwik.example.com/" : "http://piwik.example.com/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Code -->
</body>
</html>
Under the following assumptions:
https is never used
we don't care that the page loads slower because the script is loaded before the DOM
is it okay to convert the above to the following:
HTML file:
<html>
<head>
[...]
<script src="http://piwik.example.com/piwik.js" type="text/javascript"></script>
</head>
<body>
[...]
<noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
</body>
</html>
Custom Javascript file with jQuery:
$(document).ready(function() {
try {
var piwikTracker = Piwik.getTracker("http://piwik.example.com/piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
}
catch(err) {
}
}
Are there any differences?
You are deferring the tracking until the page is fully loaded. Inline Javascript is executed when the browser finds it, so you'll have different number of visits depending on where you call piwikTracker.trackPageView();. The latter you call it, the lesser number of visits/actions will be counted.
Now, what do you consider a visit/action? If a user click on a link on your page, before the page fully loads, do you consider it a visit?