Using jQuery to fetch information from iframe from different domain - javascript

I'm doing a site that fetches the stock property from a site and show it on my site.
But i'm having issue in displaying the it.
Here's the code :
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<iframe id="frame3" src="http://www.stockpart.net" sandbox="allow-forms allow-scripts allow-same-origin " style="visibility : hidden "></iframe>
<script>
$(document).ready ( function(){
$('#frame3').contents().find('.addClassClose').show();
});
</script>
I'm getting the following errors :
AD BLOCK NOT DETECTED
pop.js:1 rt():in true false tabunder 2
pop.js:1 rt():adv.bind http://serve.popads.net/servePopunder.php?cid=242978
pop.js:1 Uncaught SecurityError: Blocked a frame with origin "http://stockpart.net" from accessing a frame with origin "http://www.example.com". Protocols, domains, and ports must match.
Anyway is there anyway i can fetch information with the other site class/id using jQuery within an iframe?

I found the answer on the post posted by Patrick Evans with some modifications.
<?php
$homepage = file_get_contents('http://stockpart.net');
echo $homepage;
?>
Then put the iframe on the main page to get the stock information

Related

How to add a PHP page into blogspot.com new page

I have a real .php page like this http://hiteachers.com/soccer_parse.php?id=5. I want to add it into a blogger.com new page (**not a new blog post, or new HTML widget **, and I've got this successfully.
https://tranbongda.blogspot.com/p/function-myfunction-window.html
I used the code like this:
<script>
var Window;
// Function that open the new Window
function windowOpen() {
Window = window.open("http://hiteachers.com/soccer_parse.php?id=5",
"_blank", "width=400, height=450");
}
// function that Closes the open Window
function windowClose() {
Window.close();
}
</script>
<button onclick="windowOpen()">Open page</button>
<button onclick="windowClose()">Close page</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function()
$("button").click(function(){
$("#div1").load("http://hiteachers.com/soccer_parse.php?id=5");
});
});
</script>
My expectation is that I'd like the blogger page to load the original content of the .php page immediately when the visitor visits the blogger.com page (https://tranbongda.blogspot.com/p/function-myfunction-window.html) without clicking on any button.
I have thought of creating iframe by using this:
<iframe name="Framename" src="http://hiteachers.com/soccer_parse.php?id=5" width="550" height="550" frameborder="0" scrolling="yes" style="width: 100%;"> </iframe>
But the blogger.com page does not accept it, and returns the error message like this:
This page contains HTTP resources which may cause mixed content affecting security and user experience if blog is viewed over HTTPS.
Then I moved to try this <object width="500" height="300" type="text/html" data="http://hiteachers.com/soccer_parse.php?id=5"></object> as per some bloggers' suggestions, but I still failed.
Some other bloggers suggested to use AJAX, which is very new to me.
So, is there any way to parse the provided .php page content and add it to the blogspot.com/blogger.com new page without showing the url of the .php page or window pop-ups?
Can you help me please?
Thanks
As the bloggers likely have suggested, make the PHP server a REST endpoint and access the data on the blog site with Asynchronous JavaScript and XML. Although today people have tended to scratch the XML part and go with JSON or something.
AJAX is accomplished by using the XMLHttpRequest object.
Mozilla's spec provides links and stuff which will show you how to use it
and w3schools is a good resource.
Then it's all comes down to editing the page directly
element.removeChild(element.lastChild);
element.appendAdjacentHTML('beforeend',xhr.responseText);

How to load jQuery inside frame?

I am working on a legacy enterprise application whose code was written in 2001 using a combination of JavaScript, HTML, Intersystems Caché, and Caché Weblink.
This is what exists in index.html for the web app:
<HTML>
<HEAD>
</HEAD>
<FRAMESET ROWS="32,*" FRAMEBORDER="no" border="0" framespacing="0">
<FRAME
SRC="sysnav.html"
NAME="sysnav"
SCROLLING="no"
MARGINHEIGHT="10"
MARGINWIDTH="10"
NORESIZE>
<FRAME
SRC="cgi-bin/nph-mgwcgi?MGWLPN=dev&wlapp=SYSTEM&SystemAction=DisplayContentFrame"
NAME="content"
SCROLLING="auto"
MARGINHEIGHT="0"
MARGINWIDTH="10">
</FRAMESET>
<noframes>
</noframes>
</HTML>
The problem that I have is that in the content frame, the HTML for that frame is automatically generated every single time, but I need to include jQuery in the frame.
Is there any hack/workaround I can do to shove jQuery into the content frame?
As was alluded to in comments, jQuery could be injected into the frame as long as the frame is on the same domain.
Vanilla Javascript
A script tag like the one below could be added to the <head> element of index.html. It waits until the content frame has been loaded via addEventListener() and then dynamically adds a <script> tag with the src attribute pointing to the jQuery code hosted by the Google Hosted Libraries.
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
frames['content'].addEventListener('load', function() {
var contentFrameHead = frames["content"].document.getElementsByTagName("head")[0];
var newScriptTag = document.createElement('script');
newScriptTag.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js';
contentFrameHead.appendChild(newScriptTag);
});
});
</script>
See it demonstrated in this plunker example. Try clicking the button labeled Test jQuery Loaded in this frame? and see how the result changes when commenting line 10 of index.html.
Utilizing jQuery in index.html
Maybe it would be too much overhead, but if jQuery was added to index.html, jQuery helper functions could be used. I attempted to utilize those to shorten the code but ran into an issue while attempting to create the script tag using $() - refer to this answer for a detailed explanation of why that won't work.
So the code utilizing jQuery helper functions isn't much shorter...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>-->
<script type="text/javascript">
$(function() { //DOM-ready
$(frames['content']).on('load', function() { //load for content frame
var newScriptTag = document.createElement('script');
newScriptTag.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js';
var contentFrameHead = frames["content"].document.getElementsByTagName("head")[0];
contentFrameHead.appendChild(newScriptTag);
});
});
If content frame has a different domain
Otherwise, if the domain of the content frame is a different domain than that of index.html, then a server-side script (e.g. using PHP with cURL, nodeJS, etc.) might be necessary to fetch the content of that page and include the jQuery library (which itself might be cumbersome).
No, but you can create a new page and include that in the src. Yes it is ugly, but it could work in some cases.
include jquery in the new page, and include the old page in the new page.

How to parse a web page from a local javascript file

I need to parse a content that is dynamically generated by a javascript from a remote page.
For example, I need to get the price from this page: http://www.alibaba.com/product-detail/BRG-Newest-Fashional-Protective-Case-For_1666645206.html#J-wrapper
but the price is generated by a javascript, so when I download the page with ajax, it downloads only the html file without the results of the scripts.
So I tried to embed in the background an iframe and then parse the document inside this iframe, but there is a security issue that doesn't let me parse it.
Do you know if there is another way I can do it?
The function that I use is this:
$.ajax({
url: url,
dataType: 'text',
success: function(html, _, xhr) {});
but the resulting HTML is without the scripts information, so the price is empty.
I tried to use also:
<html lang="en">
<head>
<meta charset="utf-8">
<title>contents demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<iframe src="http://api.jquery.com/" width="80%" height="600" id="frameDemo"></iframe>
<script>
document.getElementById("frameDemo").onload = function() {
var contents = $( "#frameDemo" ).contents();
}
</script>
</body>
</html>
but I get this error:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement':
Blocked a frame with origin "null" from accessing a frame with origin "api.jquery.com".
The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "http".
Protocols must match.
Instead of using an iframe, try using a chrome app webview. It will run in a segregated container without the restrictions you referenced. But you can still communicate with it.

Redirect IF referrer matches destination

I would like to redirect to a different page if the referrer matches the loaded website. I want to do this because I run a php rotator script running simultaneously on several websites. But IF I have site A being advertised on sites A B C D, I would like site A to show only if the referrer matches site B C or D or not to show if referrer matches site A. This is to prevent showing the same website on itself.
The script is a php script loaded in an iframe. It doesn't have referrer cloaking or anything like that. I can include any javascript or php in the rotator script.
Any ideas or pointers would be appreciated. Thank you!
sorry, this is a little long, but I want to make sure this is well answered.
Let's be clear and use consistent terminology to make sure we're on the same page here:
redirect means to capture the request for the current page and point it at a different page.
For example:
typing "http://gooogle.com" into your address bar will perform a redirect to "http://google.com"
There are multiple kinds of redirects, we'll not got into them here.
referer indicates the URI that linked to the page being requested, as pulled from the HTTP headers
For example:
You're on the page "http://slate.com"
You click a link that leads you to "http://newsweek.com"
your referer is "http://slate.com" in this case.
A redirect may modify the value of the referer, depending on the type of redirect.
In order to accomplish what you wish: to not display an ad in an iframe for the page you are currently on, you are not actually concerned about either of these. You don't need any redirection, and you don't need to be concerned about who linked to the current page.
Consider how your page works:
There is a javascript that executes on page load that inserts an iframe into your document.
That iframe, in turn, loads the PHP file on the server, which displays the ad.
So you have an HTML page that looks something like this:
index.html
<!doctype HTML>
<html>
<head><title>Server A Index</title></head>
<body>
<header>
<section id="top_banner_ad">
<script src="./js/adrotator.js"></script>
</section>
</header>
<!-- Some content... -->
</body>
</html>
Which calls a JavaScript that looks something like this:
/js/adrotator.js
var holder = document.getElementById("top_banner_ad");
var iframe = document.createElement("iframe");
iframe.src = "http://example.com/inc/adrotators.php";
holder.appendChild(iframe);
Which calls, finally, a PHP script that looks something like this:
/inc/adrotators.php
<!doctype HTML>
<html>
<head><title></title></head>
<body>
<?php $advert = get_advert(); ?>
<a href="<?php echo $advert['url']; ?>">
<img src="<?php echo $advert['imgsrc']; ?>">
</a>
</body>
</html>
I'm not sure what you have access to in this scenario, but I'm going to assume you have access to all of these: the page hosting the script (index.html), the javascript that creates the iframe (/js/adrotator.js), and the php script that is called by the iframe (/inc/adrotator.php).
You have at least 2 solutions:
You can either have /js/adrotator.js find out from index.html and tell the /inc/adrotator.php who it is, or you can have /inc/adrotator.php find out who it's parent frame is.
So, the iframe has knowledge of its parent frame (though they can only actually communicate under certain circumstances)
If your iframe loads a page that is on the same domain (subdomains matter), one solution would be to have a javascript in the iframe (in the HTML generated by the PHP) check its parent, like so:
parent.document.location.href
And then request a new ad if the target domain matches the parent.
(preferred) If you can modify the javascript that creates the iframe in your page, then you could have the javascript check the url and add it as a url parameter to the src attribute of the iframe it calls.
For example:
var host_url = window.location.href;
var iframe = document.createElement("iframe");
iframe.src = "http://example.com/ad_rotator.php?host="+ host_url;
document.body.appendChild(iframe);
And then your PHP script would not serve an ad whose target matches $_GET["host"]
<?php
$advert = get_advert();
while ($advert['url'] == $_GET['host']) {
$advert = get_advert();
}
?>
<a href="<?php echo $advert['url']; ?>">
<img src="<?php echo $advert['imgsrc']; ?>">
</a>
all the code here is untested pseudo-code, you will definitely need to modify this, it's just a starter
If you can't modify the PHP that loads the ad, nor can you modify the script that injects the iframe, you're pretty much hosed.

Cant access JS function in Cross Domain Environment

In order to solve Cross Domain security woes of JavaScript, I am implementing the following method
On Domain [ abc.com ]
On domain abc.com I have a page called main_page.html. Its code is as follows -
<script>
function SendMsg(id)
{
frames["invisible_iframe"].location = "http://xyz.com/invisible_iframe.html#"+id;
}
</script>
<body>
<input type="button" id="Test" value="Call iFrame" onclick="SendMsg(this.id);">
<iframe src="ttp://xyz.com/visible_iframe.html" name="visible_iframe" height="250" width="500"></iframe>
<iframe name="invisible_iframe" height="0" width="0" style="display:none;"></iframe>
</body>
On Domain [ xyz.com ]
On domain xyz.com I have a page called visible_iframe.html. Its code is as follows -
<script>
function Hi()
{
alert("Hi there!");
}
</script>
<body>
<h1>Visible iFrame on xyz.com
<iframe name="d2_invisible_iframe" id="d2_invisible_iframe" class="iFrame" src="http://xyz.com/invisible_iframe.html" height="310" width="520"></iframe>
</body>
Now I want to access the function Hi() from invisible_iframe.html (which is on the same domain)
The code of invisible_iframe.html is as follows
<script>
var sActionText = "";
function CheckForMessages()
{
if(location.hash != sActionText)
{
sActionText = location.hash;
var sAction = "";
var oSplitActionText = sActionText.split("#");
sAction = oSplitActionText[1];
if (sAction == "Test")
{
parent.Hi();
}
}
}
setInterval(CheckForMessages, 200);
</script>
<body>
<h1>Invisible iFrame on xyz.com</h1>
</body>
I am using hidden iFrame in visible_iframe.html because I don't want the URL of visible_iframe.html to change.
Now I expect when the button on main_page.html is clicked, I'd get alert message. But that doesn't happen. In firefox it says - Permission denied to access property 'Hi'
The strange thing is when I put parent.Hi(); outside CheckForMessages() function, the Hi() function can be accessed and alert box is shown.
What should I do to resolve this ?
Why not using easyXDM? This library should make your life really easy and help to avoid the security limitations when dealling with cross domain issues. Specially if you have control over the two domains.
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
[This is one of the best and easy to use APIs] available for Cross Domain Communication between web applications.
easyXDM is easy to use, light weight, flexible, writing good quality code etc. I strongly think if you are going to continue with cross domain scenario, then you should adapt a robust cross domain apis such as easyXDM.
[easyXDM vs PostMessage Transport?]
easyXDM will use the PostMessageTransport method if this feature is enabled by the browser such as (IE8+, Opera 9+, Firefox 3+, Safari 4+,Chrome 2+) on the other side it will use different transport methods for the un supported browsers such as (Firefox 1-2 - using the FrameElementTransport) other transport methods will be used as needed such as FlashTransport, NameTransport, and HashTransport).
This clearly makes easyXDM superior in terms on browser support specially the old browsers.
To demonstrate cross-domain access using easyXDM (Domain1 [abc.com] calls a method on a remote domain [xyz.com]):
*On Domain [ abc.com ] - main domain*
<script type="text/javascript">
/**
* Request the use of the JSON object
*/
easyXDM.DomHelper.requiresJSON("../json2.js");
</script>
<script type="text/javascript">
var remote;
window.onload = function(){
/**
* When the window is finished loading start setting up the interface
*/
remote = new easyXDM.Interface(/** The channel configuration */{
/**
* Register the url to hash.html, this must be an absolute path
* or a path relative to the root.
* #field
*/
local: "/hash.html",
/**
* Register the url to the remote interface
* #field
*/
remote: "http://YOUR.OTHER.DOMAIN/YOUR_APPLICATION/YourRemoteApplication.html",
/**
* Register the DOMElement that the generated IFrame should be inserted into
*/
container: document.getElementById("embedded")
}, /** The interface configuration */ {
remote: {
remoteApplicationMethod: {},
noOp: {
isVoid: true
}
},
local: {
alertMessage: {
method: function(msg){
alert(msg);
},
isVoid: true
}
}
},/**The onReady handler*/ function(){
/**
* Call a method on the other side
*/
remote.noOp();
});
}
function callRemoteApplicationMethod(Value1, Value2){
remote.remoteApplicationMethod(Value1, Value2, function(result){
alert("Results from remote application" + result);
});
}
</script>
In the body
<input type="button" onclick="callRemoteApplicationMethod(3,5)" value="call remoteApplicationMethod on remote domain"/>
Now on your remote domain side you need to define your remote client as follows
*On Domain [ xyz.com ] - Remote domain*
This should go into the page YOUR_APPLICATION/YourRemoteApplication.html
<script type="text/javascript">
/**
* Request the use of the JSON object
*/
easyXDM.DomHelper.requiresJSON("../json2.js");
</script>
<script type="text/javascript">
var channel, remote;
/**
* When the window is finished loading start setting up the channel
*/
window.onload = function(){
/**
* When the channel is ready we create the interface
*/
remote = new easyXDM.Interface(/** The channel configuration*/{}, /** The configuration */ {
remote: {
alertMessage: {
isVoid: true
}
},
local: {
remoteApplicationMethod: {
method: doSomething(value1, value2){
// do somethigs with values
return "i'm return value from remote domain";
}
},
noOp: {
isVoid: true,
method: function(){
alert("Method not returning any data");
}
}
}
});
}
</script>
I suppose there is no need to suport old browsers, right?
You can use window.postMessage in modern browsers to support cross-origin communication.
You won't believe the cause. On main_page.html (abc.com) you define two iframes but you don't close them (missing </iframe>). Now there are two cases:
Case 1:
iframes are independent so your main_page.html code should be
<iframe src="http://xyz.com/visible_iframe.html" ...></iframe>
<iframe src="http://xyz.com/invisible_iframe.html" ...></iframe>
and the javascript call from invisible_iframe.html should be
parent.frames["visible_iframe"].Hi();
Case 2:
iframes are parent and child so main_page.html code should be
<iframe src="http://xyz.com/visible_iframe.html" ...></iframe>
visible_iframe.html code sould include
<iframe src="http://xyz.com/invisible_iframe.html" ...></iframe>
and the javascript call from invisible_iframe.html should be
parent.Hi();
That's all. The choice is yours.
Assuming your onlcick works on your input (just a typo there): from invisible_frame, you should address visible_frame's Hi() with parent.frames['visible_frame'].Hi().
For now, parent.Hi() tries to access a Hi() located on abc.com's page (as it is the frame's parent), so you're poked with the hard stick of Same Origin Policy.
Hope this helps and works ;)
Try creating these three files:
http://abc.com/main.html:
<!DOCTYPE html>
<html>
<head>
<script>
function SendMsg(id) {
window.frames.invisible.location = 'http://xyz.com/invisible.html#' + id;
}
</script>
</head>
<body>
<input type="button" id="Test" value="Call iFrame" onclick="SendMsg(this.id);">
<iframe src="http://xyz.com/visible.html" name="visible" height="250" width="500"></iframe>
<iframe name="invisible" height="0" width="0" style="display:none;"></iframe>
</body>
</html>
http://xyz.com/visible.html:
<!DOCTYPE html>
<html>
<head>
<script>
function Hi() {
alert('Hi there!');
}
</script>
</head>
<body>
<h1>Visible on xyz.com</h1>
</body>
</html>
http://xyz.com/invisible.html:
<!DOCTYPE html>
<html>
<head>
<script>
var sActionText = "";
function CheckForMessages() {
if (location.hash != sActionText) {
sActionText = location.hash;
var sAction = "";
var oSplitActionText = sActionText.split("#");
sAction = oSplitActionText[1];
if (sAction == "Test") {
parent.frames.visible.Hi();
}
}
}
setInterval(CheckForMessages, 200);
</script>
</head>
<body>
<h1>Invisible on xyz.com</h1>
</body>
</html>
Notice that the frame structure is:
main
/ \
/ \
visible invisible
And so if you need to access visible from invisible, you need to go:
parent.frames.visible.Hi()
Moving forward, I suggest using easyXDM or the jQuery postMessage plugin for cross-domain communication instead of reinventing the wheel.
There is a reason it is not letting you access the function because of the same origin policy. It would cause real security issues if you could.
CORS (Cross-Origin Resource Sharing) or window.postMessage (ref: Docs on MDN or another simple postMessage example) are definitely worth investigating if you don't care about IE7 support; you could also use a postMessage shim for older IE browsers.
However, I'll stick with an iframe solution in an attempt to more precisely answer your question.
Unfortunately you should not be able to access the parent (window scope) properties/methods from a cross domain iframe. However you can access window scopes via iframes on the same domain ...at any depth. Thus, one solution is to leverage vertical iframe tunnels.
If you create three html documents:
Top level - abc.com
<script>
function sendMsg( id ) {
frames["invisible_iframe"].location = "//xyz.com/mid_level.html#" + id;
}
window.ACTIONS = {
Test: function() {
alert("hello");
// This action could also start an interaction with another
// visible iframe by setting a hash, etc
}
};
</script>
<input type="button" id="Test" value="Call iFrame" onclick="sendMsg(this.id);">
<iframe name="invisible_iframe" height="0" width="0" frameborder="0" style="visibility:hidden;" src="//xyz.com/mid_level.html"></iframe>
Mid Level - xyz.com
<script>
function sendMsg( id ) {
frames["invisible_iframe"].location = "//abc.com/low_level.html#" + id;
}
var sActionText = "";
function checkForMessages() {
if(location.hash != sActionText) {
sActionText = location.hash.replace(/^#/, "");
location.hash = "";
sendMsg(sActionText);
}
}
setInterval(checkForMessages, 20);
</script>
<iframe name="invisible_iframe" height="0" width="0" frameborder="0" style="visibility:hidden;" src="//abc.com/low_level.html"></iframe>
Low Level - abc.com
<script>
function runActionInTop( action ) {
try {
window.top.ACTIONS[action]();
} catch ( err ) {
// Bad action!
}
}
var sActionText = "";
function checkForMessages() {
if(location.hash != sActionText) {
sActionText = location.hash.replace(/^#/, "");
location.hash = "";
runActionInTop(sActionText);
}
}
setInterval(checkForMessages, 20);
</script>
These three iframes can communicate - the first and third can communicate directly and the second indirectly (via hash in this example).
I know this is a variation from what you were originally trying to show with the "visible iframe". I wanted to focus on illustrating the layering necessary for the cross-site communication. If you still need the visible iframe, you could add communication hooks at the top level and also send additional information (in the hash) back from the middle frame to the lowest frame (the lowest frame could then communicate the information directly back to the top page).
Yes, I know this is convoluted - that is one of the reasons why CORS and postMessage exist :)
I've also changed a few minor aspects of your original code that I think are worth pointing out:
Using // instead of http:// means that this system will work on either http or https.
Some browsers (I believe I first ran into this with Safari 3) may not actually load the iframe with display:none; setting the frameborder attribute and visibility:hidden will keep the iframe from being visible.
Some browsers will load about:blank (or a similar page) if you do not specify the iframe src attribute in the markup. On https pages, this can cause insecure content warnings to be thrown in IE.
An alternative, Proxying.
In server-side grab the external file and echo it back. Now it is on your domain so no issues.
for example in php
<?php
$external-site = file_get_contents('http://xyz.com/');
echo $external-site;
?>
I think I would delete any iframes and use jsonp maybe with a library.
1. No Cross-domain errors
2. You could get data as objects (easy to play with 'em
3. You could even get JS code that u could parse.
4. Would be even mobile ready ( iframes are last century solutions... )
But then well maybe you are not able to take away the iframes for any reasons, so I advice to use a ready-made library solution.
Goodluck

Categories

Resources