New tag and parser in HTML - javascript

I've sketched out a new programming language for client side scripting. I'm familiar with how to build a language, and most of the work that goes into it. I'm prepared for a long project but have a few questions about how to implement it into a HTML file. I'd like to implement something like the <script> tag in HTML, and I've found a few links that explain how to add a new tag to HTML. I figure developers will have to connect to a js file with the language parser (it's actually more than a parser, but that's besides the point) in the head of their HTML file, like so: <script src="my-lang.js"></script>. Here are some of the links I've found:
https://blog.teamtreehouse.com/create-custom-html-elements-2
https://developers.google.com/web/fundamentals/web-components/customelements
Here are some of my questions, assuming I want my language between <my-language> tags:
How do I prevent the browser's HTML parser from misinterpreting whatever is in the <my-language> tags as HTML code? All the code in my language would show up as plain text on the website from what I can see.
How can I implement my parser into the JS file? I'm not asking how to parse a custom language, just where to put it. The first link mentions a createdCallback() function that is called when a <my-language> tag is used. Assuming nobody adds a <my-language> tag with JavaScript later (which for this language that would be pointless) that callback should be called anytime the custom tag is used.
To parse my language, should I access the innerHTML attribute of my custom tag? I don't know if by parsing time the tag even has that attribute, or if I have to add that attribute, as I'm not familiar with how that part of it works.
Thanks for putting up with my silly questions. I like to dive into the deep end with this stuff even though I'm fairly new at this part of scripting. Basically, this is what I want the code to look like:
<!DOCTYPE html>
<html>
<head><script src="my-lang.js"></script></head>
<my-language>
//do some stuff in my language, like DOM editing.
//Just a replacement for JavaScript basically that doesn't serve much purpose.
</my-language>
</html>
Any suggestions would be appreciated. Thanks in advance!

Rather than using a new nonstandard tag in the HTML, I would recommend considering using a <script> tag. Although <script> tags are often for Javascript, this is not always the case. For example, one possible technique for the server to send data for the client's JS to parse is to put JSON in a tag like <script type="application/json">{"foo":"bar"}</script>. Scripts with types other than type="javascript" will not be attempted to be parsed as Javascript, but the data inside the tag can be retrieved with Javascript. You can do that by selecting the tag and then accessing its textContent property. (The innerHTML property is probably only appropriate when you deliberately want to retrieve HTML markup - otherwise, probably best to use textContent)
You can use nearly the same technique, but rather than JSON.parseing the content of the <script> tag, send it through your parser.
For example:
const tag = document.querySelector('script[type="myNewLanguage"]');
const scriptText = tag.textContent;
// use your parser to parse scriptText
scriptText.split('\n').forEach(line => {
console.log(line);
});
<script type="myNewLanguage">foo
bar
baz</script>

Related

How to embed javascript file content into html page in Thymeleaf?

I need to embed javascript directly into html page generated by Thymeleaf
Something like:
<script th:include="../static/assets/generated/scripts.js"></script>
But this simple usage leads to SAXParseException...
Is there any easy way to switch off parsing of the th:included
content? Or any other way how to embed content of resource int the result page?
I don't think that is possible out of the box. You could probably write an extension that can do it. Or maybe there is an existing one, but I couldn't find one right now.
Does it have to to be a separate JavaScript file? Can't you put your JavaScript code into a fragment and include it like any other fragment?
NB: Including JavaScript into your HTML file like that is usually bad web design und may be a sign that you have bigger problems and you haven't structured your code well. Why do you think you need to do that? Why can't you refer to an external script file?
Thats not a Thymeleaf-Thing. It's classic html:
<script src="/assets/generated/scripts.js"></script>
In version 3.0, you can do it in this way
<script th:src="#{/webjars/jquery/dist/jquery.min.js}"></script>

Are there better ways of inserting HTML into the DOM than insertAdjacentHTML() and a huge HTML string?

I need to insert a large amount of HTML into the DOM.
My current way of doing this is copy-pasting the HTML I need to insert into a JS file, formatting it such that it's bug-free within the string, and then using insertAdjacentHTML() to insert.
Having a huge, multi-line string of copy-pasted HTML in the JS just feels dirty every time I happen to scroll through it.
The only constraint is that I really want to avoid using libraries if I can.
Better in this case is pretty much a secure implementation that's an improvement in readability.
Even if you don't wish to use a HTML templating tool, you can still include the HTML in a similar manner.
The handlebars.js site includes some examples, such as including the HTML in the .html file itself, selecting the element, and parsing its contents:
You can deliver a template to the browser by including it in a tag.
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
Compile a template in JavaScript by using Handlebars.compile
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
In your case, you could replace the type property in the html to anything obvious, and retrieve the contents by calling document.querySelector("htmlString").innerHTML.
Other options include loading the HTML as a separate file via AJAX, or if you're daring, writing your own transpiler to stick the HTML in the Javascript for you (which is basically what React does with JSX)
One last thing to consider: you will want to ensure that the injected HTML doesn't include any potential XSS vulnerabilities or that any DOM events won't get screwed up as a result of adding the HTML (though using insertAdjacentHTML should prevent events from breaking).
Also, consider looking over this HTML injection code I wrote awhile back to ensure you're avoiding (some but not all) possible pitfalls:
https://github.com/jsweeneydev/HTMLTemplate/blob/master/htmltemplate.js
Good luck!

How do I load an mbox content without inserting into the dom

I'm trying to interface with Adobe Test & Target because I want to load JSON rather than markup through my mbox. I want to load some mbox content into javascript and manually add it to the DOM. I have searched all over for full documentation of the mbox.js but I can't find anything other than the very basics. It describes how to use mboxDefine() and mboxUpdate to target a specific dom element. Is there a function that just returns the content?
```
T&T does not offer a function to assign the response to a javascript variable. Basically the way it works is mbox.js builds a url to their server and then then outputs a script include tag. This is done to get around the same origin policy limitations (cross-site scripting).
In order to handle whatever is in the html offer, they put it in their own javascript variable on their server and then output it as that as the response. However, they also have the response output the code that updates the target element. So there's nothing you can do to actually stop them from updating the target element with the html offer contents. They simply don't expose that.
However, you don't have to put html in an html offer. You can put json (javascript) in an html offer. Just do like
html offer 'myJsonMbox' (in interface)
<script type='text/javascript'>
var myJsonString = "[json string]";
</script>
Then on your page (inside your body tag, but before your code that wants to use it) you'd have the regular mbox code:
<div class='mboxDefault'></div>
<script type='test/javascript'>
mboxCreate('myJsonMbox');
</script>
And then somewhere after that, where you're wanting to do something with it, that myJsonString is there for you to reference. Or, you can do it with the mboxDefine and mboxUpdate sometime after page load, if you prefer.
Is there some particular reason why you don't think this will work for you?
You can:
a- Insert JS code you are going to use to manually manipulate the DOM
b- Insert CSS code you can use to alter the original HTMl or the newly added HTML.
c- Insert a call to a 3rd party script that will load content from a 3rd party server if needed, or the same server.

Parsing HTML using JavaScript

I'm working a page that needs to fetch info from some other pages and then display parts of that information/data on the current page.
I have the HTML source code that I need to parse in a string. I'm looking for a library that can help me do this easily. (I just need to extract specific tags and the text they contain)
The HTML is well formed (All closing/ending tags present).
I've looked at some options but they are all being extremely difficult to work with for various reasons.
I've tried the following solutions:
jkl-parsexml library (The library js file itself throws up HTTPError 101)
jQuery.parseXML Utility (Didn't find much documentation/many examples to figure out what to do)
XPATH (The Execute statement is not working but the JS Error Console shows no errors)
And so I'm looking for a more user friendly library or anything(tutorials/books/references/documentation) that can let me use the aforementioned tools better, more easily and efficiently.
An Ideal solution would be something like BeautifulSoup available in Python.
Using jQuery, it would be as simple as $(HTMLstring); to create a jQuery object with the HTML data from the string inside it (this DOM would be disconnected from your document). From there it's very easy to do whatever you want with it--and traversing the loaded data is, of course, a cinch with jQuery.
You can do something like this:
$("string with html here").find("jquery selector")
$("string with html here") this will create a document fragment and put an html into it (basically, it will parse your HTML). And find will search for elements in that document fragment (and only inside it). At the same time it will not put it in page DOM

Javascript redirect to dynamically created HTML

I have a javascript routine that dynamically creates an HTML page, complete with it's own head and script tags.
If I take the contents of the string and save it to a file, and view the file in a browser, all is well, but if I try document.write(newHTML), it doesn't behave the same. The javascript in the header of the dynamic newHTML is quite complicated, and I cannot include it here... But please believe me that it works great if I save it to a file, but not if I try to replace the current page with it using document.write. What possible pitfalls could be contributing to this that I'm not considering? Do I possibly need to delete the existing script tags in the existing header first? Do I need to manually re-call onLoad??
Again, it works great when the string is saved to, for example, 'sample.html' and browsed to, but if I set var Samp="[REAL HTML HERE]"; and then say document.write(Samp); document.close(); the javascript routines are not executing correctly.
Any hints as to what I could be missing?
Is there another/better way to dynamically replace the content of the page, other than document.write?
Could I somehow redirect to the new page despite the fact that doesn't exist on disk or on a server, but is only in a string in memory? I would hate to have to upload the entire file to my server simply to re-download again it to view it.
How can I, using javascript, replace the current content of the current page with entirely new content including complex client-side javascripting, dynamically, and always get exactly the same result as if I saved the string to the server as an html file and redirected to it?
How can I 'redirect' to an HTML file that only exists as a client-side string?
You can do this:
var win=window.open("") //open new window and write to it
var html = generate_html();
win.document.write(html)
win.document.close();
Maybe eval() function would help here? It's hard to give ansver without seeing the code.
Never tried this, but i think it should be possible. Some thoughts on what might make it work:
Make sure the document containing your js is sent with the correct headers / mimetype / doctype
Serve the javascript in a valid way, for example by sending a w3c valid page containing the script tag.
Maybe then it works. If not, try to erase the current html before writing the new one.
Also, it might be helpful to look how others managed to accomplish this task. If i remind it correctly, the google page is also essentially a short html page with a bunch of js.

Categories