Add HTML/JS code to external web page after it has loaded - javascript

Is it possible to load an external web page like 'http://www.google.com' and then append my own HTML/JS code to the end of it (e.g. to run a function)?? Surely there is a way to load an external page then add a little bit of my own code after it? Something like this:
<html>
<script>
document.location.href="http://www.google.com/"; //Load external page
function myscript() {
...blahblah
}
</script>
<button onclick="myscript();">Click me</button>
</html>
I'd like that button to be at the bottom of the external page. Please do not suggest parsing methods in php. I've tried doing this by parsing the page first in php then appending my own script to it and echoing as I described here:
Append HTML to page after redirect
This works for simple pages where there are no re-directs or when the final external page can be parsed properly. The problem is that I can't properly parse the external page. The code that is parsed doesn't seem to function without the code from previous pages (before the re-directs). I need to do this without parsing/scraping/crawling.
Thanks!
EDIT: I've tried displaying the external page in an iframe as suggested by Amadan:
<script>
function myscript() {
...blahblah
}
</script>
<iframe src="http://www.google.com/"></iframe>
<button onclick="myscript();">Click me</button>
</html>
However, in firefox it just displays a blank box but in IE it says "This content cannot be displayed in a frame: To help protect the security of information you enter into this website, the publisher of this content does not allow it to be displayed in a frame."
Any way I can get around this?
EDIT 2:
I've included jquery and the cross domain script here (https://github.com/padolsey/jquery.fn/blob/master/cross-domain-ajax/jquery.xdomainajax.js). This is the code I'm using now to get the contents using ajax. How would I go from that to actually displaying the content in the webpage? Sorry I'm really bad with ajax/jquery!
function test () {
$.ajax({
url: 'http://www.google.com/',
type: 'GET',
success: function(res) {
var content = $(res.responseText).text();
alert(content);
}
});
}

You can't append anything to a page you don't control except by installing a browser extension (which then works only for the clients where your extension installed).
You can include the contents of a page you don't control inside your own page (in two main ways: client-side iframe and server-side pull), but you seem to be saying this is not what you want.

Try something like this:
var html = '';
$.ajax({
uri: 'http://ya.ru',
method: 'POST',
success: function(data){
htmlx = data;
}
});
About manipulating html inside an variable
var test = $("<div/>");
test.append(html);
test.find(".innertest");
// When I'm ready to append it..
$('#container').append(test);
If it doesn't work, you can use another page on your server for getting a remote page and use ajax to request it.

Related

Ajax submit script global

I have this piece of code. this code has to be inside every new loaded ajax page. cause if its outside, it wont work.
example:
<div> Loaded form here , including the script </div> <- works
<div><div> Loaded form here , </div> script is here </div> <- do not work
Q: How can i make it able to work without the need to put this script on every of my ajax pages?
code:
<script>
$("form").on("submit",function(e) {
e.preventDefault();
var btn= $(this).find("input[type=submit]:focus");
$('<input>').attr({
type: 'hidden',
name: btn.attr('name'),
value: btn.val()
}).appendTo('form');
action = $("form").attr('action');
$.post(action, $(this).serialize(), function(data) {
$(".main_center").html(data);
});
return false; // prevent normal submit
});
</script>
if the script is in the loaded file, it will proccess correctly. but if it isnt, it will just refresh the page. cause the loaded file will not find the script that is ment to be used.
Is your script in the .main_center div?
If so then the returned data will replace it - hence you need to include your script in the data returned in your ajax call.
Putting the script into a common js file included in your footer works (I've done it myself) so the fault is almost certainly with the structure of your document and the way you are replacing content.
Will need to see a more of the actual code to properly advise you.
[Edit] Have you tried
<div class="main_center">
<div><form> ....</form></div>
</div>
<script>
$(document).on("submit","form", function(e){ ... });
</script>
This binds the script to the document and calls it whenever a form is submitted, including forms loaded after the page has been generated

How to execute JS code after redirect to page with href link?

I have a page with a function like this:
$.ajax({
type: "POST",
url: "checkLogin.php"
})
.done(function( msg ) {
alert(msg );
if (msg != "true"){
window.location.replace("index.html");
}
});
This function checks if a Session is alive on Server. If not it will redirect to index.html.
On first call of this .html it works. But if I go to this page with a href link when the page was loaded before the page isn't executing any JS.
How can I call that JS again?
When I am open up an other page without loading that page with javascript before and click the href link it works.
Something with Cache?
Try using window.location.replace("index.html"); replace() removes the URL of the current document from the document history, meaning that it is not possible to go back.
What you could do is append the index.html string with index.htlm#something and then detect that (something) onload/on document-ready for the index page, and execute the code you want
edit: ie window.location.replace("index.html#session_check");
and on the index page, use
if(window.location.href.indexOf("#session_check") != -1) {
// code here
}
According to my limited knowledge JS scripts from a different HTML file are not executed due to security reasons. If you want to execute the JS scripts you need to use the eval(str) function call. Where str is the JS scripts serialized to a string.
A second approach would be to create a "script" tag dynamically and supply the src attribute pointing to the desired JS file. When the script tag is placed in the DOM the script should hopefully be executed.

Get text from body tag of another page hosted on another domain - javascript / Jquery

Suppose a webpage www.example.com/some.html hosed on server. Now I want to get the content inside body tag of that page from another domain. How can I do it? I tried to find solution, but no luck with that yet.
Here are some ways that I thought and found.
First one can get content of a tag from same site.
$.get("link.html", function(data) {
var html = $('<div>').html(data);
var content = html.find("div#some_div_id").html();
//do something
$("#Container").html(content);
});
use .get() to get html of a div in another page
I tried, but doesn't work for me. I think it's because of my cross domain request.
Second idea is using iframe. Wanna load the page into iframe and extract body tag. But can't find any solution regarding how can I detect the event that iframe completed loading the page? Or how can I get the content from an iframe loaded page?
Can anyone please tell me how can I get those content from the body tag in a simple way?? Is there any solution just like my first example? Please help...
This works.
var bodycontent;
$("<div>").load("link.html body", function (data) {
bodycontent = data;
});
If I was you, though, I would do it using something server-side. This is because many websites use Access-Control-Allow-Origin to block the files, and make you unable to access it. This is also a form of impersonation and hacking, so use it in moderation.
This is not possible without a server-side proxy to request the other site's content; Javascript is not capable of making cross domain requests due to the same origin policy. You can't do this with an iframe or AJAX, server-side proxy only.
try this
$.ajax({
url: "your_url",
data: dataToSubmit,
async: false,
success: function(response) {
$('.your_div').html(response);
}
});
you may also use load
$('body').load("your_url");
$.get("URL", function(data) {
data = data.replace(/\n|\r|\t/gmi,'');
/<body>(.*)<\/body>/i.test(data);
data = RegExp.$1;
});
If you want parse HTML,using regular expressions is better

Loading content into a div using jQuery's load method

I am trying to load the contents into a div named rightcontent into my page from external html files using the jQuery's load method. Initially, there is no content in my div rightcontent, and as the user clicks some links, the texts are automatically loaded into that div.
Take a look at these snippets :
In my web page:
<div id="rightcontent">
</div>
The same web page also contains links like these:
<a class="myajaxreq" href="pages/abc.html">Link I</a><br>
<a class="myajaxreq" href="pages/pqr.html">Link II</a>
The external javascript file contains these code:
$('.myajaxreq').click(function() {
var myhref=$(this).attr('href');
$('#rightcontent').load(myhref);
return false;
});
When I check whether my javascript calls are made correctly using alert(myhref), it works correctly. However, no content is loaded into the div. Help me out here !!
Are you testing the code locally or on a server? AJAX requests won't work locally.
Upload it to a server (and put everything in the right subdirectories) and it should work fine.
use
$('#rightcontent').text(myhref);
instaed of
$('#rightcontent').load(myhref);
Try using
$(".myajaxreq").click(function(){
$.get( $(this).attr("href"), function(page){
$("#rightcontent").html(page);
})
return false;
})

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Categories

Resources