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.
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
On my index page there are two links for Login and Signup and one iframe
I have designed both(Login and signup) pages separately
Now i want to force both pages to be opened only in iframe not in a separate tab
and if someone tries to access directly redirect them to index page.
here is my code...
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Login Signup
<iframe src="" name="frame" frameborder="0"></iframe>
</body>
</html>
You can add the following to the head of your HTMl document to make it automatically redirect if it is not loaded inside an iframe:
<script>
window.onload = function(){
if (top === self) {
//not inside iframe
location = 'url';
}
}
</script>
JSFiddle: http://jsfiddle.net/xjqyrsd7/
I just found the Best way to do it with Javascript..
var myUrl = 'http://localhost/test/index.php';
if(window.top.location.href !== myUrl) {
window.top.location.href = myUrl;
}
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>
let's assume that the content is empty as given below.
<head>
</head>
If I want to change it dynamically to
<head>
<script src="jquery-1.8.0.min.js"></script>
</head>
is there anyway that AppInventor can do that?
You can select it and add to it as normal:
$('head').append('</script>');
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
script=document.createElement('</script>');
script.src='src';
document.getElementsByTagName('head')[0].appendChild(script);
Some simple javascript to change the innerHtml of document.head will work
document.head.innerHTML = "<script src=\"jquery-1.8.0.min.js\"></script>";
How about:
var HeadScript = document.createElement("SCRIPT")
HeadScript.src = "jquery-1.8.0.min.js"
document.head.appendChild(HeadScript)