I would like to generate a clickable URL that contains a starting URL string + document.title + another string + response.text. The link text should be "click here"
This is my code
<!DOCTYPE html>
<html>
<head>
<script>
'use strict';
var res = "";
(async () => {
let response = await fetch('https://httpbin.org/encoding/utf8');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 10));
// I want to generate a clickable uri that contains starting url+document.title+another string+response.text. The link text should be "click here"
document.getElementById("demo").innerHTML = 'Click Here';
})()
</script>
<title>My File Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p> Generate clickable URL from parameters. <a id="demo"></a><br>
<p id="KK1"></p>
</body>
</html>
When I run this code the URL generated only contains the starting URL string, i.e. "https://www.google.com/search?". But I want the full URL to contain starting URL + document.title + another string + response.text.
Starting URL: https://www.google.com/search?
document.title: The page title
Another string: Any string
response.text: The string received from fetch
Looking forward for your help. Thanks all.
I'm not exactly sure what you are trying to do but this gets stuff and makes a link.
fetch('https://httpbin.org/encoding/utf8')
.then((response) => {
return response.text();
})
.then((text) => {
document.getElementById("KK1").innerHTML = text.slice(0, 10);
document.getElementById("demo").href = `https://www.google.com/search?${document.title}another string${text}`;
});
<html>
<head>
<title>My File Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<a id="demo">Click Here</a><br>
<p id="KK1"></p>
</body>
</html>
Related
I want to have JavaScript to get a user's URL and return the source code of the website. I want to have this to essentially make an iframe, but with the actual code.
E.g. :
let userUrl = prompt("What website do you want displayed?","e.g. https://www.google.com");
function getSource(url){
//some code
return pageSource;
}
document.body.innerHtml=getSource(userUrl);
I tried to scrape a view page source website and turn it into an API that I could inject into JavaScript, but I had no luck.
<html>
<head><meta charset="us-ascii">
<title></title>
<script>
let userUrl = prompt("What website do you want displayed?","e.g.
https://www.google.com");
if (userUrl){
var srcFrame=""; //complete page code to inject into your iframe or return
var fetchMe = "https://example.com?q=" + userUrl;
fetch(fetchMe).then((response) => response.text()).then((text) => {
srcFrame = text;
//if injecting into iframe
myFrame.document.open();
myFrame.document.write(srcFrame);
myFrame.document.close();
// USE THE FOLLOWING TO ADD THE ORIGINAL URL AS THE baseURI SO RELATIVE
//LINKS & SCRIPTS WILL WORK AND ACCESS THE ORIGINAL SOURCE AND NOT YOUR
//SERVER
var addOrigBase= document.createElement('base');
addOrigBase.setAttribute('href',userUrl);
document.getElementById("myFrame").contentDocument.head.appendChild(addOrigBase);
});
};
</script>
</head>
<body>
<iframe onload="myFrame.frameElement.height =
(myFrame.frameElement.contentDocument.body.clientHeight)+10" frameborder=""
height="25px" id="myFrame" name="myFrame" scrolling="no" src="about:blank"
width="100%"></iframe>
</body>
</html>
(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123#example.com
(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname
(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.
I tried the following successfully :
<!doctype html>
<html>
<head>
<body>
<div>
<p id ="dd"></p>
</div>
<meta charset="UTF-8"/>
<script type="text/javascript">
var iid=document.getElementById("dd");
var getURL=window.location.href;
var theString = window.location.href;
var theWord = "fname";
var theWordExp = /fname/g;
if (theString.search(theWordExp) == -1) { window.location.href=
('www.example.com/error-page'); };
</script>
</body>
</head>
</html>
Explanation:
"I want to check Current URL Parameter whether it contains any data in fname"
The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?
basically it's almost the same as your approach using the location href to parse the params
"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)
Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method
const getQueryParam = (name) => {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
let fnameParam = getQueryParam("fname");
if (!fnameParam) {
window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>
<head>
<body>
<div>
<p id="dd"></p>
</div>
</body>
</head>
</html>
My code goal is to search various websites at once.
I would like to do this while generating a query string with the search terms.(Mainly for analytics reasons). I use a form to do so.
With java-script I add the search term name to the array of links linkList.
Written from bits of code I found online, worked "fine" before adding the form part to generate my query string. Now it doesn't even display the links.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/scripts"></script>
<body>
<form id="test-form">
<div>
<input type="text" name="search" placeholder="Search"id="id"/>
<button type="submit" id="go">get links</button> </div> </form>
<div id="linkText"></div>
<div id="a">test</div>
</body>
</html>
Javascript
$(document).ready(function(){
//READ URL
let params = (new URL(document.location)).searchParams;
let name = params.get("search");
console.log(name)
//IF QUERY IN URL
if(name !== null && name !== '') {
// do something
}
else {
//ARRAY LIST 1
var linkList = {
"https://google.net":"Click",
"https://google.org=":"Click2",
};
//LINK GENERATION FROM ARRAY
for (link in linkList) {
if (linkList.hasOwnProperty(link)) {
var a = document.createElement('a'),
linkText = document.createTextNode(linkList[link]);
//ADD THE QUERY AT THE END OF THE LINK
a.href = link + name;
a.appendChild(linkText);
document.body.appendChild(a);
}
}
}
});
Found an easier solution that solved my problem :
I search the URL for the query parameters and call them name
let params = (new URL(document.location)).searchParams;
let name = params.get("search");
But I create the links in a less complicated manner
document.write('Link Name');
var foo = "http:example.com/search="+name;
I would label my coding skills as intermediate thus what I am asking may or may not be simple or obvious (I wouldn't know the difference). Also I sincerely thank any and everyone who gives this even an ounce of attention.
My objective is to grab raw song metadata from another server (in which I am a client of) via the jsonp and ajax method. Once I successfully obtain the metadata (Artist, Title & album), I then would like to display it in my website’s page title (please see pics below).
The reason I would like to do this is because from what I could gather via an extensive and worn out research, it seems that most Bluetooth Audio devices are reading the metadata from the page title (browser tab):
Google Music playing in browser
BT Audio player
What I would love to do seems like it should be simple to do, yet I cannot figure away to display "Artist, Title and Album" in my browser like Spotify, Youtube or Google Music does.
My code below is able to pull the raw data, convert it using jsonp and I can successfully push only ONE element from the raw data (IE 'title') by placing it as an ID element. However, how can I push all three (Artist, Title & Album) to the page title?
<!DOCTYPE html>
<html
lang=en
dir="ltr"
class="mobile-web-player"
>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title;
var artist = document.getElementById('artist');
artist.innerHTML = 'by ' + metadataObj.m_Item2.Artist;
var album = document.getElementById('album');
album.innerHTML = metadataObj.m_Item2.Album + ' ';
}
}
</script>
<script type="text/javascript">
var stationID = 'X123';
var apiToken = 'X12345';
// refresh MetaData every 5 seconds
function fetchMetadata(stationID, apiToken) {
$.ajax({
type: 'get',
cache: false,
url: "https://listen.samcloud.com/webapi/station/X123/history/npe?token=X12345&callback=update&format=json",
//async: true,
datatype: 'jsonp',
});
}
fetchMetadata(stationID, apiToken);
window.setInterval(function() {
fetchMetadata(stationID, apiToken);
}, 5000);
</script>
<!-- I can successfully send the song's title to my page title via <title id> method -->
<title id="title">My Radio Station</title>
</head>
<body>
</body>
</html>
In your update() function you can call document.title to set the new tab title instead of setting the <title> tag. For example:
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
var artist = document.getElementById('artist');
var album = document.getElementById('album');
// If you are using es6
document.title = `Playing ${title} from ${artist} - ${album}`;
// If not using es6
// document.title = 'Playing '+ title + ' from '+ artist +' - album';
}
}
You could change your update function to the following to write Artist, Title, and Album to the web pages title.
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title + ' ' + metadataObj.m_Item2.Album + ' ' + metadataObj.m_Item2.Artist;
}
}
I want to create a dynamic URL. The domain part should remain the same. For example: In this URL "https://www.google.com/search?", I want to append content fetched from another website.
I use this js to fetch and store result to Html element "KK1"
<script>
'use strict';
(async () => {
let response = await fetch('https://api.com/values/1');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
Assuming the response received from fetch is amoeba1, I want to generate a URL like "https://www.google.com/search?amoeba1"
My code
<!DOCTYPE html>
<html>
<head><script>
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>
How do I append the fetched string? The string is already in
<p id="KK1"></p>
Looking Forward to getting help.
You are looking for anchor tag & you want to add dynamic href:
<!DOCTYPE html>
<html>
<head><script>
'use strict';
var res = "";
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ text;
document.getElementById("demo").href = "https://www.google.com/search?"+ encodeURI(text);
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<a id="demo"></a><br>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>
document.getElementById("demo").innerHTML = "https://www.google.com/search?" + document.getElementById("KK1").innerHTML
Maybe you can modify your script to store in a variable the text result from your API call then with template literals, using ${} you can build your new string for demo element.
Like the following
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
Or there are other ways to concatenate a string like:
'https://www.google.com/search?' + resultText
Read further here: Template literals (Template strings)
Update:
So you need to merge those two <script> tags what you have.
I guess this will do that job for you:
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
// essential modified part:
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
})();
And don't forget to remove this one:
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
I hope that helps!