Writing a string to text file with Javascript - 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.

Related

submit form via JS

I have created a chrome extension which send a form to GTmetrix.
This is the html code:
<html>
<head>
<title>GTmetrix Analyzer</title>
<script src="popup.js"></script>
</head>
<body>
<h1>GTmetrix Analyzer</h1>
<button id="checkPage">Check this page now!</button>
</body>
</html>
This is the JS file:
document.addEventListener('DOMContentLoaded', function() {
console.log("f")
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
console.log("f")
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
var i = d.createElement('input');
i.type = '';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
console.log("a")
console.log(f)
});
}, false);
}, false);
I added the console.log events in order make sure that the code is executed, however, I expect the html to present the submitted form, including the response. The issue is that I only get the tab url added to the html when I click on the button due to(d.body.appendChild(f);) so I am not sure why I can't see it.
You can try this another approach of d.body.appendchild(f):
document.getElementsByTagName('body')[0].appendChild(f);
or have a null checker like this:
if ( document.body != null )
{
document.body.appendChild(element);
}

Change part of link with part of current URL

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>

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);
};

window onload conflicts with body onload javascript

My client puts our below JS code in his website in the <head> and is complaining our tags are not firing. Below is the sample code from client:
<html>
<head>
<script type="text/javascript">
function create() {
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
var existing = window.onload;
window.onload = function() {
if (existing) {
existing();
}
create();
}
</script>
</head>
<body onload="javascript:clientfunction();">
<script type="text/javascript">
function clientfunction()
{
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</html>
On page Load clientfunction() is calling, our create() function is not firing.
Please can anybody help me why our tags are not firing and what is the alternative solution for this issue?
copy paste and check running following
<html>
<head>
<script type="text/javascript">
function create() {
alert("Gdfg");
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
window.onload=create;
window.onload=clientfunction;
</script>
</head>
<body onload="clientfunction(); create()">
<script type="text/javascript">
function clientfunction()
{
alert("fdsfsdf");
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</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