Dynamically insert and execute a script resource - javascript

Hope I can explain this properly. We are currently inserting this external JS in our HTML:
<script src="https://NotOurDomain.com/SomeScript.js"></script>
The code in this script resource is something like this:
var callbackUrl = encodeURIComponent(window.location.href);
var token = encodeURIComponent('eidoasjdiojancoxjnegkjasd');
var url = 'https://NotOurDomain.com/path?token=' + token + '&callbackUrl=' + callbackUrl;
document.open();
document.write('<iframe src="' + url + '"></iframe>');
document.close();
This all works fine, but now I need to insert this dynamically. Problem is, I can't just copy the code in this script resource because the "token" part changes periodically.
How can I get this to work? Is it possible to load https://NotOurDomain.com/SomeScript.js as a string and parse out the token so that I could create and insert an iframe with the correct URL? Or is there a simpler way of doing this?
This obviously does not work because a script include will only execute on load:
jQuery('#someDiv').append('<script src="https://NotOurDomain.com/SomeScript.js"></script>');
But is there some way to get it to "eval" after inserting?

Related

Sanitizing parameters passed from url to iframe src attribute

On domain-one.com an iframe elements get written through javascript with the code below.
The src attribute url of that iframe needs to receive the url parameters that are given to domain-one.com
e.g.
domain-one.com?par1=value1&par2=value2
<script type="text/javascript">
var params = window.location.search.substring(1);
if (params && params.length > 0) {
document.write('<iframe src="https://example.com/page?col=2&' + params + '"></iframe>');
}
else {
document.write('<iframe src="https://example.com/page"></iframe>');
}
</script>
With this code any number of params and any value can be given to domain-one.com.
This feels rather unsecure.
What is best practice to minimize the risks? Does this needs escaping or encoding?
What vulnerability can be executed client side by using the code above.
Thanks in advance

getJSON is adding the previos URL. jQuery

I have an Spring Server with HTML pages with Thymeleaf Engine and I am using jQuery for making a getJSON:
When my server is redirecting to that URL localhost:8080/redirect_admin/ where is the the next peace of code:
<table>
<tr>
<td>
<input type="text" class="add_youtube_link" th:id="${id_local}" />
<input type="button" id="upload_youtube_links" onclick="add_youtube_link()" value="Add new Youtube Link"/>
</td>
</tr>
</table>
Where I can add a link to add in my server. Well, when I click on onclick the next Javascript function will run:
function add_youtube_link()
{
var url2 = "add_youtube_link/"+$(".add_youtube_link").attr('id')+"/"+$(".add_youtube_link").val().replace(/\//g,"_");
alert(url2);
$.getJSON(url2, function (data) {
// window.location = "redirect_media/"+$(".add_youtube_link").attr('id');
});
}
So, the alert function is showing correctly the new URL: add_youtube_link/1/ZyDO4FUVxXk untill this point all is OK.
But, if I take a look in the Network Log on Chrome, the URL called is:
GET http://localhost:8080/redirect_media/add_youtube_link/1/ZyDO4FUVxXk 404 (Not Found) .
So, the problem is that the previous URL redirect_admin/ is adding automatically in the new URL. Anyone knows how to solve it?
Thank you
Its always a good idea to use a base url in your code, so you don't face issues like this:
var baseUrl = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
Then include that base url with any url
var url2 = baseUrl + "add_youtube_link/"+$(".add_youtube_link").attr('id')+"/"+$(".add_youtube_link").val().replace(/\//g,"_");
Usually this kind of error happens when your physical script file's address is different from your html page.The solution is that we always pass the partial address from the context where the function is called and in this case is your html page.

exchange variables between html files in javascript

I am trying to share variables between two html pages. I am only using javascript and HTML5 to develop a windows 8 app. Based on an image which a user clicks on one page, I want a div on a second page to be populated with that image. Any ideas?
When I click on the image, I am currently calling the following function:
function imageClick(url) {
//var id = parsed.ClientID;
//window.location= url + "?" + id
window.location = url;
}
Then in my html file, I have this line:
<img onclick="imageClick('pages/page2/page2.html')"
data-win-bind="src:image" style="width: 133px; height: 125.5px;">
I was thinking of getting that id in the next page's url (if I were to uncomment the commented lines above) but it's a bit hackky and I don't actually know how to go about executing the retrieval of that on the next page..
Is there a more efficient and easy way of doing this in javascript? Like an equivalent of sessions in php or something?
Javascript does not have session variables because it runs on the client side. You can use URL parameters and cookies in order to achieve the same results.
You can get the URL parameter by using this function:
http://ziemecki.net/content/javascript-parsing-url-parameters
Add the link to the image to the query part of the url when they click. Something like you had in the comment, assuming you don't have a query part already:
function imageClick(url) {
//var id = parsed.ClientID;
window.location= url + "?src=" + url.src;
//window.location = url;
}
The other page can use window.location.search to extract it, strip off the src=. The code would look something like this:
var src = window.location.search;
if (src.indexOf("src=") == 0) {
src = src.substring(4);
}
newPageImageElement.src = src;
Where newPageImageElement is the <img> where you want to display the picture on the second page.

Do we need a web server (like Apache) to access a .json file?

I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.
$.getJSON('info.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.
Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).
Thanks in advance.
You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.
origin null is not allowed by access-control-allow-origin
Host your page on localhost server and I guess everything will work nicely.
While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.
Install a small webserver like http://jetty.codehaus.org/jetty/
easy to install, and small download ;)
By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)
var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.

Creating Bookmarklet: Append current URL with specific string

I am attempting to create a bookmarklet that will change the URL of the page I am currently on, and load a new page with the URL string changed. I have reviewed a number of other threads on bookmarklets, but I haven't found a solution that works for me.
I would like to be able to change a URL that looks like this:
http://mywebsite.com/directory/page.html?referral=Google&visit=1
to:
http://mywebsite.com/directory/page.html?dog=Fido&cat=Mittens
The three goals:
1) Delete anything in the existing URL after the ? mark.
2) Append "dog=Charlie&cat=Mittens" after the question mark.
3) Immediately load this new page, with the new URL
It seems simple enough, but I have not been able to figure out how to do this. Any help would be greatly appreciated!
Try this:
javascript: window.location = window.location.protocol + '//' + window.location.hostname + window.location.pathname + '?dog=Charlie&cat=Mittens';

Categories

Resources