Here is my HTML and I want to show source code of url with (view-source+url) inside class .source-html from input when I click on button?
const input = document.querySelector("#input");
const button = document.querySelector(".view");
button.addEventListener("click", (x) => {
const url = input.value;
const sourceUrl = "view-source:" + url;
//Some code that show source of url inside div
});
<input id="input" type="text" />
<button type="button" class="view">View Source</button>
<div class="source-html"></div>
If possible, help me.
The modern browsers not allowed to load local source of the website. This is due to security policies. If you load other websites source into your site, then there is a chance to load malicious scripts.
Still if you try to load the view-source then you may encounter with "CORS error" or "Not allowed to load local resource: view-source:"
You can still use the below code to view the source of same origin sites.
const input = document.querySelector("#input");
const button = document.querySelector(".view");
button.addEventListener("click", (x) => {
const url = input.value;
//view source of same origin
$.ajax({
url: url,
success: function(x){
console.log(x);
}
})
});
Related
I want a link "Run this in " just below each PRE-CODE block.
The link should popup a new tab with any online compiler/interpreter and the code of the block.
I don't know if there is a solution already done. Like highlight.js but do this. So I tried my own approach unsuccessfully. I want to keep the HTML simple and clean.
Picked jdoodle as starting point, but the idea is to have options.
The HTML form, works! Either by redirecting or by changing the target to a new tab.
Now I want this working without the HTML FORM (to keep the HTML simple and clean) and do this in a javascript function call.
With XMLHttpRequest to perform the POST call, I get errors on CORS policy.
Access to XMLHttpRequest at 'https://www.jdoodle.com/api/redirect-to-post/execute-lua-online/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I believe that this doesn't happens with HTML-FORM because it redirects and origin gets to be the same.
So I tried unsuccessfully to either use XMLHttpRequest to redirect or popup into jdoodle but I cant get to transfer the POST data containing the code.
My non-working-javascript-example
<pre><code class="language-lua">
print("hello jdoodle")
</code></pre>
Run this on jDoodle.
<form id="inputform" method="post" action=
"https://www.jdoodle.com/api/redirect-to-post/execute-lua-online/" target="_blank">
<textarea name="initScript"
rows="4" cols="20">
print("Either redirecting or in a tab, it works!")
</textarea>
<br/><br/>
<input type="submit" value="Test">
</form>
<script>
function runthis(caller) {
prev_el = caller.previousElementSibling;
code_el = prev_el.getElementsByTagName("CODE")[0];
code_str = code_el.innerText;
alert(code_str);
var handle=window.open("https://www.jdoodle.com/api/redirect-to-post/execute-lua-online/");
const http = new XMLHttpRequest();
http.open('POST', 'https://www.jdoodle.com/api/redirect-to-post/execute-lua-online/', true);
http.onload = function () {
console.log(this.responseText);
};
FD = new FormData();
FD.append('initScript', code_str);
FD.append('submit', 'Test');
alert(JSON.stringify(FD)); // it shows empty ¿why?
http.send(FD);
}
</script>
Answering my own question, but I would always appreciate better alternatives.
As the HTML Form was working, the first step is to reproduce this in javascript, and this is not done with XMLHttpRequest.
function runthis_on_external_site(pre_elem, url, textareaname="initScript" ) {
code_el = pre_elem.getElementsByTagName("CODE")[0];
code_str = code_el.innerText;
var form_elem = document.createElement("FORM");
form_elem.method = "POST";
form_elem.action = url;
form_elem.target = "_blank";
var element1 = document.createElement("TEXTAREA");
element1.name=textareaname;
element1.innerHTML = code_str;
form_elem.appendChild(element1);
document.body.appendChild(form_elem);
form_elem.submit();
form_elem.remove();
}
Then a link must be added below each <PRE><CODE> block after the page is loaded.
function insert_A_tag_after_( pre_elem, inner, url, textareaname) {
A = document.createElement("A");
A.className = 'ref';
A.href = '#';
A.innerHTML = inner;
A.onclick = function() {
runthis_on_external_site( pre_elem, url, textareaname);
};
pre_elem.parentNode.insertBefore(A, pre_elem.nextSibling);
}
//========================================================
window.addEventListener('DOMContentLoaded', function() {
console.log('Adding external Compilers/Interpreters');
document.querySelectorAll( 'code' ).forEach((e) => {
if( e.classList.contains( 'language-lua' ) ){
url = "https://www.jdoodle.com/api/redirect-to-post/execute-lua-online/";
insert_A_tag_after_( e.parentNode, "jDoodle", url, "initScript" );
url = "https://www.lua.org/cgi-bin/demo";
insert_A_tag_after_( e.parentNode, "lua.org", url, "input" );
}
})
});
NOTE: that, I have only found jDoodle and lua.org/cgi-bin/demo so far to be able to get the code from a POST variable. Others online compilers would be appreciated.
NOTE2: I picked the class name as 'language-lua' for compatibility with highlight.js
NOTE3: As far as I could research, I couldn't found any other popular alternative solution for this. Most solutions are to embed a compiler/editor from only one site.
See my below code. It's working fine but while downloading a file by entering the required key, the file name changed and it's downloading with the whole domain name + directory + file name. But I want just the file name.
Code :
//This is the HTML part.
<center>
<input class="keyBox" style="padding : 10px; padding-left:15px; padding-right:15px" type="text" width="100px" placeholder="Enter your download key">
<br><br>
<div class="text-center">
<button id="down" class="btn btn-style btn-primary">Download</button>
</div>
</center>
// This is the Script I am using.
<script>
const files = [{
key: 12345,
path: 'Marouf.png'
}, {
key: 12477,
path: 'Ismat.png'
}]
const globalPath = 'https://abcd.com/directory/certificates/'
const inp = document.querySelector('.keyBox')
const btn = document.querySelector('#down')
btn.addEventListener('click', downloadURI)
function downloadURI() {
if (inp.value) {
let uri = files.filter(f => f.key === Number(inp.value))
if (uri.length) {
let link = document.createElement("a");
const fullPath = globalPath + uri[0].path
link.download = fullPath;
link.href = fullPath;
link.click();
} else {
alert("Incorrect download key! Try again...")
}
}
}
</script>
There are multiple ways to solve your problem. The most simple solution is to set the download attribute without value
link.download = '';
This will use the final segment of the URL as filename.
download
Causes the browser to treat the linked URL as a download. Can be used with or without a value:
Without a value, the browser will suggest a filename/extension, generated from various sources:
The Content-Disposition HTTP header
The final segment in the URL path
The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)
Defining a value suggests it as the filename. / and \ characters are converted to underscores (_). Filesystems may forbid
other characters in filenames, so browsers will adjust the suggested
name if necessary.
MDN
I am trying to submit a form in JS, however I believe the endpoint URI specified in the action attribute does not consider the relative path of the HTML document.I think this may be due to the fact that the JS script and HMTL document are not located in the same directory. The HTML doc is index.html:
<!DOCTYPE html>
<html>
<body>
<div>
student name:
<input type="text" class="studentName"></input>
<button type="button" id="addStudentButton">Add</button>
</div>
<script src="/cdn/scripts/class/index.js"></script>
</body>
</html>
The imported JS script index.js is:
const addButton = document.getElementById('addStudentButton')
addButton.addEventListener('click', function () {
const studentName = document.getElementsByClassName('studentName')[0]
const form = document.createElement('form')
const element1 = document.createElement('input')
form.method = 'POST'
form.action = '/api/create'
element1.name = 'student'
element1.value = studentName.value
form.appendChild(element1)
document.body.appendChild(form)
form.submit()
})
When the form is submitted I get the following error response in chrome:
Cannot POST /api/create
This is because it should instead POST to /class/api/create, so I figured I should change the form attribute action accordingly to:
form.action = '/class/api/create'
however I then get the error response:
Cannot POST /class/class/api/create
Does anyone have any idea what the issue is?
I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.
The user will type in their individual API key before pressing a button, revealing the API data.
Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.
<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>
.
<body>
Enter API key: <input type="text" id="apikey">
<button id="btn">Click me</button>
<p id="title"></p>
</body>
The API data which I am trying to just extract the name from, looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:
Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn');
var apikey = document.getElementById("apikey").value;
[...]
});
How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET?
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least.
Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.
It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.
Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>
There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.
No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
There is some infos to parse into the webRTC header.
var p = new window.RTCPeerConnection();
p.createDataChannel(null);
p.createOffer().then((d) => p.setLocalDescription(d))
p.onicecandidate = (e) => console.log(p.localDescription)
An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);
Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?
Page.Request.UserHostName
HttpRequest.UserHostName
The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...