Change part of link with part of current URL - javascript

I´m new on this and I´m having a hard time tryng to do something I think must be simple.
I have a lot of pages hosted on https://www.something.com/path/NUMBER/path/path
Inside those pages I have a button that links to https://www.example.com/path/REPLACE/path
I would like to change REPLACE on my link with NUMBER on the address bar.
This is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;
pathArray = window.location.pathname.split( '/' );
var part_2 = pathArray[2];
var mylink = "https://www.example.com/path/" + part_2 + "/path/page.html";
});
</script>
<p>BUTTON</p>
</body>
</html>
Thank you very much for your help!

try this.
Url1:- https://www.something.com/path/NUMBER/path/path;
Url2:- https://www.example.com/path/REPLACE/path;
url2 = url2.split('/').map(a => {
if(a == 'REPLACE')
return 'NUMBER';
else
return a;
}).join('/');

If you want to change using Javascript, you can do as below:
var url = "https://www.something.com/path/NUMBER/path/path";
var oldUrl = "https://www.example.com/path/REPLACE/path/path";
var regex = /https:\/\/www\.something\.com\/path\/(\w*?)\/.*/g;
var match = regex.exec(url);
oldUrl = oldUrl.replace("/REPLACE/", "/"+match[1]+"/");
console.log(oldUrl);
-- EDIT --
Another example to replace using browser URL and replace the second path without considering the remaining URL or paths .
$(document).ready(function() {
var url = window.location.href;
// As the script executed in iframe, assigning with hardcode value
url = "https://stackoverflow.com/questions/51442637/change-part-of-link-with-part-of-current-url#";
var oldUrl = "https://www.example.com/path/REPLACE/path/path";
var regex = /https:\/\/\w*?\.?\w*?\.\w*?\/\w*?\/(\w*?)\/.*/g;
var match = regex.exec(url);
oldUrl = oldUrl.replace("/REPLACE/", "/" + match[1] + "/");
document.getElementById("mylink").href = oldUrl;
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<p>BUTTON</p>
</body>
</html>

Related

Cannot reproduce query param html injection

We have an embedded script running on the page of one our clients. We received a report from them that the query params we send to that page are not properly guarded against XSS injection.
When I try a url like:
https://www.clientsite.com?somekey=%3Csvg%20onload%3Dalert(document.cookie)%3E
on their site, I indeed get the alert panel displaying the cookies.
But when I run our script locally, I cannot reproduce this injection. The alert panel never shows up, no matter what I put in the query param's value.
A very simplified version of the script is:
<html lang="en">
<head>
<meta charset="utf-8">
<title>XSS test</title>
</head>
<body>
<div id="content"></div>
<script>
(function() {
var url = window.location.href
var someKey = 'somekey'
var regexS = "[\\?&]"+someKey+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
var parentElement = document.querySelector('#content');
var widget = document.createElement('div');
// var svgInjection = '<svg onload=alert("alert!!")>'
// var svgEncodedInjection = '%3Csvg%20onload%3Dalert("alert!!")%3E'
widget.innerHTML = '<div>' + results[1] + '</div>';
return parentElement.insertBefore(widget, parentElement.firstChild);
})()
</script>
</body>
</html>
I don't understand how an identical script, receiving identical query params, shows an alert panel on the client's site, and nothing when I run it locally. Any thoughts?

JS automated click not working

EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};

Writing a string to text file with Javascript

We are attempting to save a URL stored in a string to a text file, but we can't seem to get it to work. It will not save into the file, although our testing shows that the function is actually running when it should be.
The code for this is here:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="instagramclick()">Login to instagram</button>
<button onclick="myFunction()">Test Button</button>
<script>
function myFunction() {
alert("Hello World");
}
function instagramclick(){
alert("button clicked");
window.location.href = "https://instagram.com/oauth/authorize/?client_id=8a612cd650344523808233c0468c80ed&redirect_uri=http://u-ahmed.github.io/HookedUp/instagram.html&response_type=token";
}
function WriteDemo(link)
{
var fso, f, r;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("database.txt", ForWriting, true);
f.Write(link);
f.Close();
r = f.ReadLine();
return(r);
}
window.onload = function writedamnyou(){
var token = window.location.href.substring(62);
if (token != ""){
// document.write(token);
var link = "https://api.instagram.com/v1/users/self/feed?access_token=" + token;
// w = window.open('database.txt')
WriteDemo(link);
// document.write(stuff);
}
};
</script>
<p id="no"></p>
</body>
</html>
Thanks in advance.

How to download JS appended values as a HTML file?

I want to download appended valu as a HTML file.
here this is my code. values append from out html file through iframe.
this code working well and retrive correct value.
I just want to download that appended value as complete new HTML file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Iframe export</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<iframe src="iframe.html" id="aaa"></iframe>
AAA
<script type="text/javascript">
function aaa()
{
var aaa=document.getElementById('aaa').contentWindow.document.body.innerHTML;
$("body").append(aaa);
}
</script>
</body>
</html>
Can you please help me to resolve this problem.
thanks in advance.
You can use a dummy <a> tag with a download attribute and a data URI:
function aaa()
{
var aaa=document.getElementById('aaa').contentWindow.document.body.innerHTML;
var link = document.createElement("a");
link.download = "filename.html";
link.href = "data:text/html," + aaa;
document.body.appendChild(link);
link.click();
}
Example
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = aaa;
createDownloadLink("#download",str,"newsletter.html");
});

Get URL parameters in JS and embed into a JS function

I have a graph library that I use to plot some data.
This data comes passed as a GET paramater in the URL in the following format: plottedgraph.html?case_id=4&otherparam=blabla
Then I have my HTML page where I try to catch that GET param with the GUP function (below) and add it to my JS function as follows: "http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted"
This is the whole HTML
<html>
<head>
<!--[if IE]>
<script type="text/javascript" src="js/excanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="js/dygraph-combined.js"></script>
<script type="javascript">
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</head>
<body>
<div id="graphdiv2" style="width:1800; height:900px;"></div>
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted", // path to CSV file
{
showRoller: true,
colors: ["rgb(255,100,100)",
"rgb(72,61,139)"]
} // options
);
</script>
</body>
</html>
Unfortunately the JS function doesn't recognize that case_id=4 in this case...
Could you please let me know what am I doing wrong?
It's a bit hard to debug you gup() function, could you try:
var params={};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
You can now find your parameters in the params object, so params['case_id'] will hold the value you're looking for.

Categories

Resources