Pulling already loaded JS into a local variable - javascript

The source of linked to .js is not available via the DOM currently.
var b = document.createElement("script");
b.type= "text/javascript";
b.src = "foo/source/ArcJ.js" // dynamically load .js file
Can I just do
var c = b.src // probably not
I think this would just give me the path...I want the source...i.e. all the code in a string.
Is there a way to do this with out using ajax? Shouldn't this be a simple DOM Pull...
document.getElementById(b.id).source_code
?

.src is the url, so you just load the url from that using an ajax request...
$.get($("script[src*=jquery]").attr("src"),function(data){
console.log(data)
})

Took from How do I get source code from a webpage? (written by me)
There is three way in javascript :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});

Related

jQuery append to vanilla javascript issue when injecting a facebook pixel in the dom

I have written a script which I have in the head section on my landing pages. What it does is that it loads a facebook pixel which I have stored in another part of my application which I access by calling an endpoint. This because I need to dynamically change the script without interfering with the code on the landing page itself. This code is written in Jquery but now I need jQuery gone from my application so I've tried to rewrite it using only vanilla javascript.
The problem is that it works just fine with the jQuery code, but when I've tried to replace it with vanilla Javascript it does not seem to inject the code in the correct way. The output in the DOM looks exactly the same but it does not fire the pixel somehow.
So my question is. Why is this?
Here is the working example of my jQuery script
<script>
$.get('https://api.mydomain.com/script', function (data) {
$('head').append(data);
});
</script>
Here is my vanilla Javascript version
<script>
var theUrl = 'https://api.mydomain.com/script';
let xhr = new XMLHttpRequest();
xhr.open("GET", theUrl);
xhr.send();
xhr.onload = function() {
document.querySelector("head").insertAdjacentHTML("beforeend", xhr.response);
};
</script>
I think the issue is with insertAdjacentHTML - just a guess, but maybe it only works for HTML (divs, images, etc.) rather than scripts. Hopefully this workaround is an acceptable solution:
(function() {
const
exampleScript = getScriptContent(`
<script>
alert("example script loaded");
<\/script>
`),
s = document.createElement("script"),
t = document.createTextNode(exampleScript);
s.appendChild(t);
document.getElementsByTagName("head")[0].appendChild(s);
function getScriptContent(htmlStr) {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlStr;
return tempDiv.innerText;
}
})();

Loading a .txt File into a JavaScript Variable without Selecting

I've asked this question before but did not explain it well enough so here's a better attempt:
I am making an application that will be run client-side, not server side. I have a .txt file in the directory with all of the code for the application, and I want to be able to automatically load the contents into a variable without the user needing to select anything. Thus, I do not want to use an input, but rather just have the file load itself when the .html page is opened. As an end result, I would want a String that contains the text inside the file.
I am not using any frameworks, just strictly coding in JavaScript, CSS, and HTML.
I assume that the answer to this question involves a Blob and using readAsText(), but even after reading the full documentation I'm unsure how to pass a URL into it so it can read the contents of a .txt file.
The easiest way of doing so is a XML request. This allows you to access the contents of files either asynchronously or synchronously. Please not that CORS will sometimes block this, so you may need to disable it if you are using chrome.
function getData(file) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", file, false);
//The false above means synchronously, true means asynchronously
xmlhttp.send();
return xmlhttp.responseText;
}
let myVar = getData("text.txt");
EDIT:
This code from Cors-anywhere at the beginning of the fuction can fix the cors policy
https://github.com/Rob--W/cors-anywhere/#documentation
(function() {
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = window.location.protocol + '//' + window.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
})();

Load text file from site files

I need to load a text file in js, the text file is in the same dir as the .js file.
I found this code
var file = new XMLHttpRequest()
file.open("GET", "file.txt", true)
file.send()
file.onreadystatechange = function () {
if (file.readyState == 4 && file.status == 200) {
console.log(file.responseText)
}
}
But that doesn't work if I open my site locally ("file:///C:/site.html")
How can I load a text if it is run locally? (Without using JQuery)
EDIT
I do not want to use JQuery but these are some questions with using JQuery.
"Ajax in Jquery does not work from local file"
or
"Jquery load() only working in firefox?"
The security policies of web browsers disallow getting file resources. You can, however, use JSONP to circumvent this:
var tag = document.createElement("script");
tag.src = 'filename.txt';
document.getElementsByTagName("head")[0].appendChild(tag);
function callback (data) {
}
You'll need filename.txt to look something like this:
callback('<text-file-content>')

Load external URL content using pure Javascript

The following JQuery gets content of an external url:
var url = 'example.com/editor/stores/10';
$('#storeArticlePublish_Channel').load(url);
I do not want to use JQuery. How would I do this using normal javascript?
You can use XMLHttpRequest object for this.To make a request:
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The 'URL' is the url you want to execute/open.
The 3rd parameter is for async request, it can be either true or false.
And to get the result in #storeArticlePublish_Channel element, you can simply use this in the next line:
document.getElementById("storeArticlePublish_Channel").innerHTML = xmlhttp.responseText;

How can I set the http RequestHeader for a file load in the $script.js library?

The $script.js library I am using
https://github.com/ded/script.js/
has the following Javascript. What I need to do is set the request header in this code block but I am not sure how to do this:
var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
return false;
}
el.onload = el.onreadystatechange = null;
loaded = true;
// done!
};
el.async = true;
el.src = path;
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);
Here's an example of something similar (not part of $script.js) that does set the request header:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
The first code block (the one I need to use but can modify slightly) is not very clear to me. Does anyone know how I can change this first code blocks (used in $script.js) to set the request header?
If I'm interpreting the library correctly, XMLHttpRequest isn't used directly by $script.js. It appears to be creating <script></script> tags dynamically and letting the browser handle downloading the script files. Using this library, it does not appear you can specify custom headers.
Altering the request headers the browser sends via Javascript is not possible according to some of the articles I've read including the answer to this question on SO: Is it possible to alter http request's header using javascript?
If you want to set custom headers, you'll need to use a dynamic loading library which uses XHR to load the scripts. Here is another article I've found with patterns for this type of functionality: On-Demand Javascript.

Categories

Resources