I want to view other website source code with javascript use in my own website, i have a code, it's showing same window, i want to view other website source code, please help me i am new programmer.
Example i want show example.com to my website as source code.
function viewSource(){;
var source = "<html>";
source += document.getElementsByTagName('html')[0].innerHTMLz;
source += "</html>";
source = source.replace(/</g, "<").replace(/>/g, ">");
source = "<pre>"+source+"</pre>";
sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
sourceWindow.document.write(source);
sourceWindow.document.close();
if(window.focus) sourceWindow.focus();
}
<button type ="button" onclick="viewSource()">View Source</button>
You could maybe try an AJAX request:
function viewSource() {
var request = new XMLHttpRequest();
request.open("GET", "someURL.com", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4)
alert(request.responseText);
};
}
This would send a GET request for the document at the URL, which should be the page source. Just be aware of the same origin policy.
Related
I am working on a project where I need to extract data from an excel file stored on client side so than i can work on that data. is there any way to do it without using any other Javascript library??
you can make a simple ajax call and get the responseText
var request = new XMLHttpRequest();
request.open("GET", "https://jsonplaceholder.typicode.com/", true);
request.onreadystatechange = function ()
{
if(request.readyState === 4)
{
var content = request.responseText;
document.querySelector('#content').innerHTML = content;
}
}
request.send();
<div id="content"></div>
On running the code in browser the spinner doesn't stop spinning i.e it keeps on loading how can I stop after the data from JSON is loaded.Link to JSON data -> http://starlord.hackerearth.com/sureify/cokestudio
<script type="text/javascript">
var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response; //request.response contains all our JSON data
showdata(myjsondata);
}
function showdata(data){
for(var i=0;i<data.length;i++){
var str = "<IMG src='"+data[i].cover_image+"'/>";
document.write(str);
}
}
</script>
See the screenshot for better understanding:
Everything looks OK here.
Open your browser's developer tools and take a look at the "Network" tab, you'll probably find the cause there.
That's probably because the images are still loading.
I'm building a static website which will relay only on client-side (no PHP).
I have couple of js and py files, which I would like to display on the site as a code.
I really want to avoid using jQuery and implement everything in JavaScript (lightweight as possible).
var codeToDisplay = "<object type='text/html' data='problem001.js'></object>";
document.getElementById('code').innerHTML = codeToDisplay;
This doesn't work. What are my options?
Thanks.
Use AJAX to get the contents of the file and insert it into the element. Use .textContent to prevent interpreting it as HTML.
var url = 'problem001.js';
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
document.getElementById('code').textContent = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.send();
<div id="code"></div>
I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};
I'm integrating an intranet with a document management system. The DMS has a SOAP API. We've built a client that receives REST calls, makes the SOAP calls, and returns JSON or document data.
The problem is all of the solutions for AJAX filedownload seem to use iFrame (see John Culniver's filedownload plugin).
I can't use this because I need to provide authentication credentials in the header. The only other potential solution I can think of is using window.open (if I can get past browser popup blocking).
Does anyone have another potential solution or how might do this with window.open??
Thanks
I don't think there is a client-side solution for this problem. window.open isn't going to let you set the request headers. You'll need to do something like send a cookie or some other value to the server and add server-side code that alleviates the need for the request header.
See the answers to:
Offer a generated file for download from jQuery post
How to set a Header field on POST a form?
I was able to do it successfully. I'm my example I'm using Basic Authentication however you can replace your Authorization header with different value (e.g you can replace it with Bearer Yourtokenvalue.
Here is the code snippet
$(document).on("click", "#btn", function() {
var username = "yourUserNameForBasicAuthentication";
var password = "yourPasswordForBasicAuthentication"
console.log("button clicked");
var request = new XMLHttpRequest();
request.open("GET", $("#txtUrl").val().trim(), true);
//Set the authorization headers
request.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
//Set the Response type as blob which means raw data
request.responseType = "blob";
//We will initiate a default file name in case no file name is detected later on from headers of HTTP Request
var fileName = "unnamed.pdf";
request.onload = function(event) {
if (request.status == 200) {
console.log("success response received");
var blob = request.response;
//Getting contenttype from response headers
var contentType = request.getResponseHeader("content-type");
if (contentType == null) {
contentType = "application/pdf";
}
//Check 'Content-Disposition' header to get filename of file (if possible)
if (request.getResponseHeader("Content-Disposition")) {
var contentDisposition = request.getResponseHeader("Content-Disposition");
fileName = contentDisposition.substring(contentType.indexOf("=") + 1);
}
if (window.navigator.msSaveOrOpenBlob) {
// Internet Explorer
window.navigator.msSaveOrOpenBlob(new Blob([blob], {
type: contentType
}), fileName);
} else {
var el = document.createElement("a");
document.body.appendChild(el);
el.href = window.URL.createObjectURL(blob);
el.download = fileName;
el.click();
el.remove();
window.URL.revokeObjectURL(el.href);
}
} //end of Status code
else {
alert("System failed to authenticate");
}
} //End of event
request.send();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="https://yoursamplefile.txt" id="txtUrl" style="width:100%" /><br />
<input type='button' value='Download File' id='btn' />