Loading contents from another page into a variable as a string [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to get the HTML of a div from another page in a variable as a string, so I can run a regex search to find a specific number?

If that other page is in your own domain:
jsBin demo
$('<div />').load("otherpage.html", function(data){
var num = /\d+/.exec( $(this).find("#number").text() );
console.log( num ); // 45
});
Note: the above presumes the desired number is somewhere inside the #number element. The regex /\d+/ is used to get all the numbers from that element.
If the page is not in your domain:
jQuery load external site page
you'll first need to get that page content using PHP with file_get_contents. After the desired content is on your server you'll not run any more into security issues and you can than respond to AJAX with the grabbed content.

If you're loading content from the same domain, the answer #lawrence overflow linked to in his comment will do the trick:Load content from external page into another page using Ajax/jQuery
JS with jQuery:
$(document).ready(function() {
$("#main").load('sourcePage.html #content');
});
Otherwise, you'll need to use server-side technology. Here's a Node.js server that proxies for another site:
JS (Node and Express):
var request=require('request');
var express = require('express');
var app = express();
//Put the source URL here:
var URL='http://www.nytimes.com';
app.get('/', function (req, res) {
res.type('.html');
request(URL,function(err,response,body){
res.send(body);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});

Related

import into the javascript frontend(html javascript) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a database called lowdb (it is a nodejs api), it is in the backend.
I want to use it in the html tag, ie the javascript frontend.
How can I import the lowdb into the frontend javascript?
First frontend = browser, backend = nodejs. You surely mean that LowDB is available as a NodeJS module, which means it can be installed with NPM, either for frontend or backend development.
If you're not using NPM for your frontend development, you can still import modules with <script> tags.
Let's see an example using only HTML/javascript:
(from the doc):
<html>
<head>
<script src="https://unpkg.com/lodash#4/lodash.min.js"></script>
<script src="https://unpkg.com/lowdb#0.17/dist/low.min.js"></script>
<script src="https://unpkg.com/lowdb#0.17/dist/LocalStorage.min.js"></script>
</head>
<body>
<button onclick="add()">Add Post</button>
<button onclick="load()">Load Post</button>
<div></div>
</body>
<script>
var adapter = new LocalStorage('db')
var db = low(adapter)
db.defaults({ posts: [] })
.write()
function add() {
// Data is automatically saved to localStorage
db.get('posts')
.push({ title: 'lowdb' })
.write()
}
function load() {
var div = document.querySelector('div')
var text = div.innerText;
text += db.get('posts').map(post=>post.title).join(';');
div.innerText = text
}
</script>
</html>
See this work: https://codepen.io/bcaure/pen/ExgBPBz

Access a page's HTML [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Is it possible to take a link and access its HTML code through that link? For example I would like to take a link from Amazon and put it within my own HTML code, use JavaScript to getElementsByClassName to get the price from that link and display it back into my HTML code.
It is possible. You could do a GET request to the Amazon page that will give you the html in the response from there you'll have a string now you'll need to format it, last time I used the node module jsdom to do that.
In more detail:
HTTP is a protocol that we use to request data from the server, I've wrote an explanatory node js script:
const https = require('https');
const JSD = require('jsdom');
const { JSDOM } = JSD;
const zlib = require('zlib');
// The http get request
https.get('https://www.amazon.com', (response) => {
html = '';
// we need this because amazon is tricky and encodes the response so it is smaller hence it is faster to send
let gunzip = zlib.createGunzip();
response.pipe(gunzip);
// we need this to get the full html page since it is too big to send in one amazon divides it to chunks
gunzip.on('data', (chunk) => {
html += chunk.toString();
});
// when the transmittion finished we can do wathever we want with it
gunzip.on('end', () => {
let amazon = new JSDOM(html);
console.log(amazon.window.document.querySelector('html').innerHTML);
});
});

NodeJS. How to create and save pdfs on the fly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
i have a form with multiple inputs. The user should insert all inputs and send it. If the form is send a PDF should be created with the inputs informations and the pdf should be saved on the Server (No display is needed).
My Question is now, if somebody knew a good plugin/ module for node.JS which can
1) Create PDF with input informations
2) Save this PDF (on Server) (This can maybe be handled with fs)
Greetings
Here is the sample code whenever you run the node server it saves the pdf file into your directory from where you are running the server.Hope this helps for you.
var express=require('express');
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8');
var options = { format: 'Letter' };
var app=express();
var file=fs.writeFileSync('C:/Users/nodejs/tasks/businesscar.pdf');
app.get('/file',function(request,response)
{
pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
var file= 'C:/Users/nodejs/tasks/businesscaw.pdf';
fs.readFile(file,function(err,data){
response.contentType("application/pdf");
response.send(data);
});
});
});
app.listen(3000,function(){
console.log("Server listening on port http://loalhost:3000");
});
See the output in browser :
localhost:3000/file

Hide Url from <a>tag on View Page Source

I am developing a website, where in i have a href tag somewhat like
xam study papers
which will open the pdf in a new tab.
Now when i open this website on google chrome and
Right Click->View Page Source
. I can see the same Content .
I want to hide the href link so i tried with javacript
<a href="#" id="id1" >xam study papers</a>
<script>
$( document ).ready(function() {
$("#id1").on("click", function () {
window.open('Folder1/Sample.pdf','_blank');
});
});
</script>
Still its showing .
So i need to hide the url . What are the best possible methods to do the same. Any help appreciated.
You cannot hide the tags from the source, because the browser require the tags for populating the website.
Use Javscript encryption.
Disable Right Click , If possible. But Cross platform issues need to
be taken care, i would prefer Javascript.
Learn on HTML encryption & javascript encryption
There is a nice article on this: How to hide your Source Code
How to encrypt HTML source code?
These question is already answered in stack please check the below link
https://stackoverflow.com/a/42952848/7751463
You could generate an Id that is paired with the URL, and send the client this unique Id. When the client makes a request with that Id to the server, you know the URL paired with that Id, then you can serve the page with that URL.
In Node, you can do that like:
'use strict';
var express = require('express');
var app = express();
var linkDict = [];
app.get('/', function (req, res) {
var id = Date.now();
linkDict[id] = 'mySecretFile.pdf';
res.send('<html><head></head><body>Secret File</body></html>');
});
app.get('/*', function (req, res) {
console.log(req);
var id = req.params[0];
res.sendFile(__dirname + '/' + linkDict[id]);
})
app.listen(3000, function () {
console.log('Listening on 3000');
})
You can hide a URL from a user, but only truely via PHP. The issue with HTML, is that the browser is still storing that information (you can dress it up with encryption, but, unltimately, you want whoever it is to read it, so they have to know how to decrypt it). Honestly, please just use php tokens for this. Some people even use entire tables in MYSQL, but for what you're doing, I think this will do.
I start by setting the header to application/pdf, this tells the browser to read the byte data as PDF and not HTML nor text. Next, I echo my hidden url's contents.
<?php
if (!empty($_GET['token'])) {
switch ($_GET['token']) {
case "1":
header("Content-type: application/pdf");
echo file_get_contents('test.pdf');
break;
}
die();
}
?>
xam study papers

How to access the dom elements of other html from current html [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Suppose the current page is some1.html, and there is a second page, some2.html. How can I access DOM elements in "some2.html" from some1.html using JavaScript?
The way you could do this is by using AJAX:
$.get(url, function(data) {
var $doc = $(data);
});
You can use that to get the contents from an url, and do something with it.
In response to your edit: You can then access the DOM elements by just doing $doc.find('selector') instead of the usual jQuery $('selector').
You can also make it a bit easier by doing:
$.get(url, function(data) {
var $doc = $(data);
var $d = $doc.find;
});
in which case you can just use the syntax $d('selector').
The way you'd do this without jQuery installed would be:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'document';
xhr.send();
xhr.onload = function(e) {
var doc = e.target.responseXML;
}
and then you can access DOM elements via doc.getElementById('id') just like you'd normally select elements, but using doc instead of document.
Note: for these functions, the $doc, $d and doc variables are only accessible within the callback function (so they're only accessible within the function where they're defined).
You cannot.
Your code shows that the new page is being loaded in the same window.
The JavaScript environment for page1 will disappear before the environment for page2 is created. Since they don't exist at the same time, you can't access the DOM of one from the other.
What you could do is store some data in localstorage or a cookie, and have code you place in page2 look for that data and run JS based on what it says.
You could experiment a bit with Ajaxh, because, as Quentin said, changing window.location.href will load the chaned file. or use an iframe like this:
var frame= document.createElement('iframe');
frame.setAttribute('src', 'some2.html');
frame.setAttribute('name', 'some2');
frame.appendTo(body);
var some2 = document.frames['name'];
//now you can acces to some2 with getElementById,...

Categories

Resources