Same Origin Policy with JavaScript extracting title - javascript

I'd like to use JavaScript with JQuery to extract a title from an HTML page, as in
$.get('page.html', function(text) {
var pagetitle = $(text).title;
});
so that when the user input a URL into a text box, I can show the title in another textbox. But this won't work if the page is outside my domain, like www.google.com, because of the Same Origin Policy. Is there some other way to achieve this functionality? It's not a crucial functionality, but I'd like to ask just in case there's some way.

You'd have to have a server-side "proxy" which goes out and fetches the page, then returns it to jQuery for processing. If you're running this in a client environment (i.e. a plain HTML file on your local PC), then there really isn't an easy way to do this.
A basic PHP script would look something like this:
<?php
echo file_get_contents($_REQUEST["url"]);
?>
Note: this is a basic demo of what you're asking for. Just this by itself could well present security risks of some sort. A better way to do this is presented in this article.
Also, though I haven't run your code, I feel like it should be more like this:
$.get('page.html', function(text) {
var pagetitle = $(text).find("title").text();
}, "html");

You can solve it!
<script src="http://kincrew.github.com/xReader/xReader.full.js"></script>
<script type="text/javascript">
xReader("http://www.google.com", "title/text()", function(data) {
alert(data.content);
})
</script>
Take a look at xReader

Related

Question mark in script breaks html

I have inserted a block of javascript in then body of a Joomla 2.5 article.
What I want to achieve is to open a default client email engine in order to send some information there.
The code looks like this:
var sendForm = function() {
...
window.open('mailto:admin#admin.com?subject=mailSubject&body=mailBody');
};
What happens actually, when I load the page is that whatever is after the "?" is broken and appears as plain text in the UI.
For example, I have the following stuff in the UI:
?subject=mailSubject&body=mailBody'); }; window.onload = getTotal();
What is wrong? Can you help me to spot the stuff that I am doing it wrong?
Thanks
It seems that this is a Joomla specific problem. I managed to get over it by using the {emailcloak=off}syntax before the actual email address.
Therefore the code looks like this mailto:{emailcloak=off}some#email.com?subject....
You might want to use ? instead of ?, and & instead of &. If you wish, you can refer to the HTML character numbers and names here.
It will not only solve your problem, but also pass the W3C validator.

Share page via url in safe way?

My index.php is making ajax post calls to ajax.php and getting echoed json as result, then parsed and displayed with js. So it is POST. I want to be able to share that result, via link like mydomain/index.php?q=foo&q1=foo1.
Here is basic pseudo-code scenario that isn't safe, I want suggestion how to achieve this in safe manner?
//index.php
//js
$.post('ajax.php', querystring, function(){
collect_result = result;
});
//ajax.php
parse($_POST);
echo json_encode(result);
// I want to be able to share result in way
http://.../index.php?q=foo&q1=foo1
//index.php
if(!empty($_GET['q]))
$querystr = http_build_query($_GET, '', '&');
<div id="div1" style="display:none"><?php echo $querystr; ?></div>
//then get it wuth jquery and make ajax.post()
$.post('ajax.php', $('#div1').html(), function(){
collect_result = result;
});
//BUT THEN USER IS ABLE TO DIRECT INJECT CODE INTO MY HTML (XSS)
//IS THERE SAFE WAY TO DO THIS SHARING VIA LINK???
Not sure if you refer to this, but as mentioned in w3schools:
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
I work with ajax on a daily basis dealing with this dilema pretty often. There are times where I have to even put password and user in a url. When sensitive data gets visible like that, I encrypt the variables. I use a php encryption method with a special key, and I decode it when I receive the variable by POST. If your are interested in this method you can look at the cbc encryption/decryption. I am sure there are others but cbc seems to be the safest. (be sure to enable the mcrypt in the php).

Store very small amount of data with javascript

I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Javascript variable to html page 'script tag'

Is it possible, if one has a javascript variable like this:
var myVariable = "alert('BAM! It works!');"
to send it to an html page that has a script tag in, in other words, looks like this:
<script id="theScriptTag"></script>
and by 'sending' I mean going like this in the Javascript file:
getElementById("theScriptTag").innerHTML = myVariable;
Now maybe people normally don't do this. If there's another way to get a Javascript variable to an HTML page please don't hessitate to tell. It's difficult for me to explain why I would like to do it like this, only that I need to do it like this.
Thanks in advance!
EDIT...
From all the comments I can see this is some serious bad practice. Let me give you the over view and 'bigger picture' here... On the very same HTML page there is a form, and a div. Now right after a user fills out the form and submits it, it goes to the server and 'custom javascript' is generated depending on the variable the user selected. This custom javascript is then intended to go back to the client and execute. When it executes is creates/fills up a div element that then contains a google charts table (thus needed to get generated server side). The JS that needs to be executed looks like this:
var sendAttemptsChartTableData, sendAttemptsChartTable;
google.load('visualization', '1', {packages:['table']})
google.setOnLoadCallback(drawTable);
function drawTable() {
sendAttemptsChartTableData = new google.visualization.DataTable();
sendAttemptsChartTableData.addColumn('string','smsGuid')
sendAttemptsChartTableData.addColumn('string','attemptNo')
sendAttemptsChartTableData.addColumn('string','response')
sendAttemptsChartTableData.addColumn('string','error')
sendAttemptsChartTableData.addRows(1)
sendAttemptsChartTableData.setCell(0,0,'092A49AA-E2EF-46D3-A83E-0932B17B649A')
sendAttemptsChartTableData.setCell(0,1,'1')
sendAttemptsChartTableData.setCell(0,2,'<aatsms><submitresult action="enqueued" key="2066317199" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317200" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317201" result="1" number="0833756610"/><submitresult action="enqueued" key="2066317202" result="1" number="0833756610"/></aatsms>')
sendAttemptsChartTableData.setCell(0,3,'')
sendAttemptsChartTable = new google.visualization.Table(document.getElementById('sendAttemptsTable'));
var view = new google.visualization.DataView(sendAttemptsChartTableData);
sendAttemptsChartTable.draw(view, {showRowNumber: true, allowHtml:false});
google.visualization.events.addListener(sendAttemptsChartTable, 'select', smsSearchHandler);
}
Based on your edit I understand your form sumbission results in a custom script. Would a JSONP-like solution work? Basically you can create a script tag in your current document, pointing its source to a server side script that processes the form and returns the code.
A basic example:
function getScript(){
/**process form, generate params**/
var nwScript = document.createElement('script');
nwScript.src = '/myscriptsrc/somescript.php?'+[generated parameters];
document.body.appendChild(nwScript);
}
If your goal is to execute the javascript code contained in the string, you can use the following :
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
What you are trying to do is essentially this:
var myVariable = "alert('BAM! It works!');";
eval(myVariable);
eval takes the string you provide and "evaluates" the content - it executes the javascript stuff you provide in the string. Normally you want to do this with input from the user.
But this is considered bad habit, because:
it is slow
it is unsecure
Usually you can go another way, so you don't need to use eval. In most cases this is cleaner, faster and more secure.
Perhaps you could tell, WHAT you are trying to achieve, and then we can find a better solution.

Categories

Resources