e.g. I have a file named: /SW1A2AA.htm
In the HTML I need to show the following image with the source for the image to include the filename (without the extension). I.e.:
<img src= "https://maps.googleapis.com/maps/api/staticmap?center=sw1a2aa&zoom=18&size=640x480">
Obviously if I need to do this for lots of pages, it would be easier if there was a way to amend the search string to depend on the filename (without the extension).
Please tell me there is a simple way to produce that result!
Thanks
Here is my solution for your example (SW1A2AA.htm). Empty src attribute is not valid, so we use //:00 - you can read more about this solution here.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
</head>
<body>
<img id="map" src="//:0">
<script>
// grab the URL. I'm working locally so in my case it is /C:/Users/myLogin/Desktop/SW1A2AA.htm
var pageURL = window.location.pathname;
// find the last position of the "/"
var fileNamePosition = pageURL.lastIndexOf("/");
// take file name and delete last 4 characters (SW1A2AA.htm -> SW1A2AA)
var fileName = pageURL.slice(fileNamePosition+1,-4);
// create src
var mapSrc = "https://maps.googleapis.com/maps/api/staticmap?center=" + fileName + "&zoom=18&size=640x480";
// update map src attribute
var map = document.getElementById("map");
map.setAttribute("src", mapSrc);
</script>
</body>
</html>
Related
I'd like to use a style sheet from Wikipedia. For that, I'm fetching this style sheet. When trying to
pass the url fetched using ajax to the head of my html document, the url retrieved behave unexpectedly.
First, I simply try to use the url as it is fetched :
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
Here is the full code :
<!DOCTYPE html>
<!-- testing purpose file, used for trying to print a correctly formatted wikipedia page -->
<html>
<head>
<meta charset="utf-8"/>
<title> game setup </title> <!-- Titre de l'onglet -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
</head>
<body style="background-color:white;">
<div class='container'>
<h1 id="title">MiniWiki</h1>
<div id="content"></div>
</div>
<script>
function loadPage() {
"use strict";
var url, doc;
console.log("IN LOADPAGE")
url = 'https://en.wikipedia.org:443/api/rest_v1/page/html/' + 'Ancient_Egypt';
// fetch the article data
return $.ajax(url).then(function (data) {
doc = (new DOMParser()).parseFromString(data, 'text/html');
// Use mediawiki content stylesheet
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
console.log("SHOW stylesheetElem");
console.log(stylesheetElem);
$('head').append(stylesheetElem);
//Update content
var contentElem = document.getElementById('content');
var $content = $(contentElem).empty();
Array.from(doc.body.attributes).forEach(function (attr) {
$content.attr(attr.name, attr.value);
});
$content.append(Array.from(doc.body.children));
});
}
loadPage();
</script>
In this case, the url fetched is
<link rel="stylesheet" href="/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
I was expecting that it would also include https://en.wikipedia.org/ at the beginning of the url like this :
<link rel="stylesheet" href="https://en.wikipedia.org/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
Since it dit not, I thought I could add it myself by simply adding this line of code just
before the line
console.log("SHOW stylesheetElem");
stylesheetElem.href = "http://en.wikipedia.org" + stylesheetElem.href
when printing the stylesheetElem url, this unexpectedly returns the following url :
http://en.wikipedia.orgfile//en.wikipedia.org/w/load.php?...kin=vector
What happened here ? Why didn't I get the following correct url ?
http://en.wikipedia.org/w/load.php?...kin=vector
The dots (...) indicate that the developer tools have left out part of the url. You copy that instead of the real url, which you can see when you do "View Page Source":
/w/load.php?lang=en&modules=ext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cskins.vector.styles.legacy&only=styles&skin=vector
I'm working on a project in which I have a simple web server hosted with node.js (see code below) and I want to be able to dynamically load the code form html files and modify them each time someone makes a request. I've already putted some marker in my code ${likeThis} and I just need the code to put a string in the right place.
Here is my server code:
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
app.listen(8080);
});
And here is an example page in which I want to change the value ${sampleText} with the plain text "hello world!!!":
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>Titler</title>
</head>
<body>
${sampleText}
</body>
Mind that there might be more of the same or different kind of value all over the html page.
On the user side I'd expect this:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>Titler</title>
</head>
<body>
Hello world!!!
</body>
There are several ways to use live data in pages returned from express. All of them utilize a "template" into which you inject "data". These include:
pug
mustache
handlebars
Another option would be to use NodeJS/ES6 template strings, such as:
const express = require('express')
const app = express()
// Text to insert into template
const sampleText = 'hello world!!!'
// Template to accept sampleText
const result = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Titler</title>
</head>
<body>
${sampleText}
</body>
</html>
`
app.get('/', function (req, res) {
res.send(result);
})
app.listen(8080);
Backticks ("`") are used to define template strings in Node where "${expression}" is used to insert any evaluable JavaScript expression into a template, like:
const result = `The contents of file ${filepath} are: ${fs.readFileSync(filepath).toString()}`
For more information, see Using Template Engines with Express
and for an exhaustive list of template engines that work "out of the box" with Express see Template Engines
i ll illustrate with Mustache, you need webpack for communication between front-side and web-server, but since webpack is headache i ll use mustache CDN.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="message"></div>
//we are gonna render the message into this div tag.
//this is a javascript code
//make sure script tags are at the bottom
<script id="message-template" type="text/html">
<div class="message">
{{message}} . //yes double curly brackets
</div>
</script>
//CDN link, Mustache pack files are stored here and we import from there
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min.js"></script>
//for src add path of index.js in your app
<script src="./index.js"></script>
</body>
</html>
index.js
//select the div that you wanna place the message
const $message = document.querySelector("#messages");
//select the script tag in
const messageTemplate = document.querySelector("#message-template").innerHTML;
const html = Mustache.render(messageTemplate, {
//I hardcoded the message here, but as you learn, you will catch a dynamic data, put it here and display in your html page
message:"hello world",
});
$message.innerHTML(html);
After a bit of work(very flew actualy) i monaged to make this function that allows me to find the strings and replace them with the correct text, i will publish it hoping someone else in the future migth need it:
function substituteString(input, stringToChange, substitute) {
var n = 0;
while (true) {
n = input.indexOf(stringToChange, n);
if (n == -1) { break; } else {
input = input.replace(stringToChange ,substitute);
}
}
return input;
}
Easier than i was thinking
I am not sure if this is possible or not...
I am trying to replace a specific part of a URL from my iframe with a string that is part of the mainframe's URL.
i.e. I am trying to replace the iframe link to include the userID.
Main URL: https://web.example.com?userID=9553c6
<iframe src="https://app.example.com?[Insert userID here]"></iframe>
If your site where is content under address https://web.example.com?userID=9553c6 in my opinion you can do this using eg. php
<body>
<iframe src="http://example.com?user_id=<?php echo urlencode($_GET['userId']) ?>"></iframe>
</body>
Then variable $_GET['userId'] will have value of 9553c6
Or you can use only js which will be a bit harder, because you have to parse location.search https://www.w3schools.com/jsref/prop_loc_search.asp and get specific part of it. Of course this value of param userId will be from main site.
Direct solution
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style>
iframe {
width: 100%;
height: 1000px;
}
</style>
</head>
<body>
<iframe src="http://fotokrajobrazy.warmia.pl/galeria/fota.php?nr=1004"></iframe>
</body>
<script>
window.onload = function () {
var res = location.search.match(/userId\=(\w+)/);
var fr = document.getElementsByTagName('iframe')[0];
fr.setAttribute('src', fr.getAttribute('src').replace(/(nr\=)\d+/, '$1'+res[1]));
};
</script>
</html>
You can then edit main url like this:
http://127.0.0.1/stack.html?userId=1003
and
http://127.0.0.1/stack.html?userId=1002
etc. and the url of iframe will change too.
You need some simple string-hangling.
You say you're injecting the frame via JavaScript, so I'll suppose your code looks something like this.
let
ifr = document.createElement('iframe'),
src = 'some/url/here?user={user-id}',
user_id = '123456';
src = src.replace('{user-id}', user_id)
;
document.body.appendChild(ifr);
The key line is the one with .replace() - that's where we replace the placeholder with the actual value.
in a Spreadsheet I have in cell A1 a number. I know how to read it and use in a html file created inside the script ( with HtmlService)
Is there a way to use the data in an external page?
On my site I'm trying to have somethin like:
<p>In your bag there are</p> + "cellA1Value" + <p>carrots</p>
Ask if I have not been clear. Thanks
Reading a value from an External Page
You will have to put the appropriate value in Sheet1!A1.
You will have to deploy as webapp and give access to anyone, even anonymous.
Then everytime you load your page it loads that value into <span id="spn1"></span>
Here's the doGet():
function doGet(e){
if(e.queryString !=='')
{
var s=SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(e.parameter.range).getValue();
}else{
var s='No Query Parameter Received';
}
return ContentService.createTextOutput(s);
}
Here's my external website code:
<html>
<head>
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
var url='https://script.google.com/macros/s/AKfycbxjlJNGYL65mItHLoL76jiEWX4iQlKzpywMAjg5SMgUUUZNbm8/exec?range=A1';
$.get(url,function(data,status){
document.getElementById('spn1').innerHTML=data;
});
});
console.log('MyCode');
</script>
</head>
<body>
<div id="mydata">The size of my ruler is <span id="spn1"></span> inches.</div>
</body>
</html>
You could use a multicell range and return a delimited string, split it and then loop through the array assigning values to different spans.
I've noticed that a browser behaves differently if I mix slashes in the href attribute of base tag. I know what base tag is used for. I'm wondering what's the difference in terms how a browser resolves the path in the following configurations:
<base href="http://domain.com/homework">
<base href="http://domain.com/homework/">
<base href="/homework">
<base href="/homework/">
<base href="homework/">
<base href="homework">
http://domain.com/homework, /homework, and homework assumes that all links on the page will be query parameters, if it start with a ?, fragments, if it starts with a #, or sub-paths if it is a string. If you add a / to the start of a link it would assume that you wanted to start at the root of the URL and would ignore whatever the base tag is set to.
Example:
<base href='http://domain.com/do-something'>
<a href='?var1=foo&var2=bar'>foobar</a> <!-- http://domain.com/do-something?var1=foo&var2=bar //-->
<a href='#home'>foobar</a> <!-- http://domain.com/do-something#foobar //-->
<a href='homework'>homework</a> <!-- http://domain.com/do-something/homework //-->
<a href='/homework'>homework</a> <!-- http://domain.com/homework //-->
By not typing out the full URL but having a / at the beginning of the href in the base tag you are implying that you want it to be at the root of the URL you are currently on. Basically /homework is shorthand for http://domain.com/homework.
Example:
Assuming you are currently on the page http://domain.com/some/page.html and you have a base set as <base href='/homework/'> then when you created a link that looks like this <a href='current'>Current</a> it would link you to `http://domain.com/homework/current.
But if you left the / off of the beginning of the base tag, so that the base tag looked like this <base href='homework/'>, then when you clicked on the same link you would be taken to http://domain.com/some/homework/current
You can just test it:
var base = document.head.appendChild(document.createElement('base')),
a = document.body.appendChild(document.createElement('a')),
urls = ["http://domain.com/homework", "http://domain.com/homework/", "/homework", "/homework/", "homework/", "homework"];
a.href = "foo";
for (var url of urls) {
base.href = url;
console.log('Using base: ' + url + '\nRelative URL: foo\nAbsolute URL: ' + a.href);
}
div.as-console-wrapper { max-height: 100%; }