submit form via JS - javascript

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

Related

Accessing JavaScript variables in target page from Chrome Dev extension

I have a simple Chrome developer extension which injects JavaScript into a target page.
It accesses the DOM no problem but will not allow me to access the variables.
<head>
<script>
window.myVar = 10;
</script>
</head>
<body>
<div id="testDiv">
some div content
</div>
</body>
Calling this snippet:
chrome.tabs.executeScript(
chrome.devtools.inspectedWindow.tabId,
{
code: scriptToExecute,
frameId: targetId
},
function(response) {
let result = [];
if(response && response.length > 0) {
result = response[0];
}
results.value = result;
}
);
This works:
scriptToExecute = document.getElementById('testDiv').innerHTML;
This returns null:
scriptToExecute = window.myVar;
Is there some way to access the variables or is it prevented for security or other reasons?

How to pass post results from one html to other html?

I want to pass results (return value of POST) from one page into other embedded page, and I don't know how can I do it.
The structures look like:
main html page (Welcome.html) which has ej2 file (Buttom.html):
Welcome.html:
<html>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// HERE I WANT TO PASS THE RESULTS TO Buttom.html
};
}); // click on submit
}); // ready
</script>
<form id="gradeForm">
<p>
<label>Name:</label>
<input type="text" name="name" id="name">
</p>
<p>
<label>Grade:</label>
<input type="text" name="grade" id="grade" value="100">
</p>
<p>
<button type="button" id="submit" >submit</button>
</p>
</form>
<div>
<%include Buttom.html%>
</div>
</body>
</html>
Buttom.html:
<head>
</head>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
}); // ready
</script>
<p id="ppp">
<!-- Here I want to add the results -->
<p>
</body>
How can I pass the results from POST (in welcome.html) to Buttom.html (i.e into function of js in Buttom.html) ?
Welcome.HTML
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// If your data is big then use cookies or create form and send it to another page
var url = "YourPage?data=" + encodeURIComponent(YOUR_DATA);
window.location.href = url;
};
}); // click on submit
}); // ready
ON Buttom.html:
$(document).ready(function(){
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null) {
// YOUR CODE
}
});
});

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.

Can I use external script along with my script in same asp.net page?

I am trying to read binary data in javascript. I got one BinaryReader.js on net. I copied that file where Default.aspx is. If I write the code like following then project got build and running but handshake is not getting done. If I remove src="BinaryReader.js" then handshake is getting done properly. So my question is, Can I use external script along with my script in same asp.net page? If yes then what am i doing wrong?
<script src="BinaryReader.js" language="javascript" type = "text/javascript">
var ws;
function btnConnectSend_onclick() {
if ("WebSocket" in window) {
ws = new WebSocket("ws://localhost:35000/");
ws.onopen = function() {
alert("Connection Open......");
};
ws.onmessage = function(evt) {
var reader = new BinaryReader(evt.data);
var tag = reader.readString(26);
//var txt = document.createTextNode(evt.data.toString());
form1.txtMessage.appendChild(tag);
};
ws.onclose = function() {
alert("Socket Closed!!!");
};
ws.onerror = function() {
alert("WTF!");
};
}
}
function btnClose_onclick() {
ws.close();
};
</script>
No, you have to create a separate script block for your code, or put it in the script file.
<script src="BinaryReader.js" language="javascript" type = "text/javascript"></script>
<script language="javascript" type = "text/javascript">
var ws;
function btnConnectSend_onclick() {
if ("WebSocket" in window) {
ws = new WebSocket("ws://localhost:35000/");
ws.onopen = function() {
alert("Connection Open......");
};
ws.onmessage = function(evt) {
var reader = new BinaryReader(evt.data);
var tag = reader.readString(26);
//var txt = document.createTextNode(evt.data.toString());
form1.txtMessage.appendChild(tag);
};
ws.onclose = function() {
alert("Socket Closed!!!");
};
ws.onerror = function() {
alert("WTF!");
};
}
}
function btnClose_onclick() {
ws.close();
};
</script>
this will add it to the page response, it will be included in the page, so that you can use it, then create one more block of script tag, and then call the functions from there.
<script src="BinaryReader.js" language="javascript" type = "text/javascript"></script>
<script type="text/javascript">
/// put your all Js Code of btnsendClick
</script>

Categories

Resources