I am trying to build a new html page based on the contents of the part of an existing html page to pass the whole thing to an api.
when I try doing something like:
var contents = $('#page-section').html();
var fullPage = $.parseHTML('<html><head><link rel="stylesheet" href="newStyle.css"></head ><body></body></html >').appendTo("body", contents);
contents variable is fine, but for fullPage I get an error. The goal is to show the "contents" with the newStyle.css
Is there any other way of achieving this?
The reason I want to do this is to pass the string to a pdf generator.
.appendTo() does not expect a second parameter. Concatenate contents withing <body></body> of HTML string. Or use DOMParser() to create a document.
var contents = $('#page-section').html();
var fullPage = `<!DOCTYPE html>
<html>
<head>
<link rel=stylesheet href=newStyle.css>
</head>
<body>${contents}</body>
</html >`;
// do stuff with `fullPage` `HTML` string
I ended up using a simple thing:
var fullPage = `<!DOCTYPE html><html><head><style></style><title>Asset Availability Report</title></head><body><div class="asset-availability-report">` + contents + `</div></body></html >`;
Related
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.
I have an html file "lobby.html" and a js file "lobby.js"
If this is in lobby.html,
<body>
<span id="lobbyCode"></span>
</body>
And this is in lobby.js,
var lobbyCode = "abcdefg";
How can I make the html file display "abcdefg"?
In your html file you need to import the external js file. Write the line below above your closing body tag to ensure it sees all the html elements.
Note: Consider that the path to your file at the src attribute value is based on your file structure.
<script src="lobby.js"></script>
</body>
You can also put it in your header
<head>
<script src="lobby.js"></script>
</head>
Then inside your external js file you are now able to access with the document.getElementById selector the inside your html file and you can update its value by setting the innerHTML property to the value of your variabel
external JS File
var lobbyCode = "abcdefg";
document.getElementById("lobbyCode").innerHTML = lobbyCode;
var lobbyCode = "abcdefg";
document.getElementById("lobbyCode").innerHTML = lobbyCode;
<body>
<span id="lobbyCode"></span>
</body>
I am trying to parse this HummingBird api with sample url :
http://hummingbird.me/api/v1/search/anime?query=naruto
However, I do not know how to get each id seperately , or each name seperately. For e.g:-
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = //make this display name
</script>
</body>
</html>
I want the demo element to display the title of the first one in the list. Can anyone tell me how I can possibly do this?
If you use jQuery below is the snippet you can use.
var results = "";
$.get("http://hummingbird.me/api/v1/search/anime?query=naruto",function(data){
results = JSON.parse(data);
});
console.log(results);
Download JQuery from here and put the file next to your html.
Add this element between the html tag and the body
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
Replace document.getElementById("demo").innerHTML = with:
$(document).ready(function(){
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null, function (data) {document.getElementById("demo").innerHTML = data[0].title})
})
JQuery is a JS library that makes life easy.
The function below takes 1 function as an argument and executes it after the page has loaded
$(document).ready()
The next function makes an HTTP GET request and parses the response to js object
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null,...)
The next function gets the title of the first element of data
function (data) {document.getElementById("demo").innerHTML = data[0].title}
mmm try this fiddle i don't know exactly how you read the file but if you get a string do the JSON.parse(STRING) before.
https://jsfiddle.net/79a1abbL/3/
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.
I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don't know if it's best to do it with jQuery or without.
$(function() {
// read JSON
alert("the json is:")
})
I would change the script declaration to this:
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
Note type and id fields. After that
var data = JSON.parse(document.getElementById('data').textContent);
will work just fine in all browsers.
The type="application/json" is needed to prevent browser from parsing it while loading.
And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.
I ended up with this JavaScript code to be independent of jQuery.
var jsonElement = document.getElementById('json-script-tag');
var myObject = JSON.parse(jsonElement.textContent);
To read JSON in <script id="myJSON"> use
var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON
You can also use methods to point to the script like document.scripts[0]
//var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
JSON.parse($('script[src="mysript.js"]').html());
or invent some other method to identify the script.
Maybe instead of .html() you might need .text(). Not sure. Try them both.