PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label xmlhttprequest. Show all posts
Showing posts with label xmlhttprequest. Show all posts

Friday, December 2, 2022

[FIXED] How to use the XMLHttpRequest api to retrieve the title of the current page loaded in an iframe?

 December 02, 2022     iframe, javascript, xmlhttprequest     No comments   

Issue

I'm working on a solid-js application that has an iframe containing a site. I am trying to obtain the title of the current page loaded in the iframe and not having the same domain name as my site. I would like to know if it is possible to get this title using the XMLHttpRequest api. Here is the code of my iframe:

<iframe
      width="100%"
      height="1300"
      id="iframeID"
      src="https://gkwhelps.herokuapp.com"
    ></iframe>

Solution

It's not possible in front-end JavaScript alone, due to security restrictions - you can't do anything with a document in a different domain unless that domain has specifically set things up to allow you do interact with it, which is quite unusual.

But it's not impossible. If you set up an app on your own server, you can have your site make a request to your server-side app, and have your app then make a request to the external site, and then either return the text of the response to your client, or parse the response yourself and send the document title to the client.

For example, in an express server, node-fetch, and JSDom, you could do something like:

fetch('https://gkwhelps.herokuapp.com')
  .then(res => res.text())
  .then((responseText) => {
    const doc = new JSDOM(responseText);
    res.send(doc.title);
  })
  // .catch(handleErrors);

And then from the client, you just need to make a fetch or an XMLHttpRequest to your app, and the title will be returned.



Answered By - CertainPerformance
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 6, 2022

[FIXED] What is the difference between ajax post request and form post request?

 September 06, 2022     ajax, html, javascript, xmlhttprequest     No comments   

Issue

on server side, for example, I use flask to handle these post requests, the same code can handle the two type requests, but on client side, ajax request will not let the browser to refresh the whole page, but the form does. So what is the difference in deep, is some header field not same?? or something else?? Thanks!


Solution

There is no difference, only that AJAX is, as the acronym suggests, asynchronous, which means it does not block anything else from running. Both the form and an AJAX request send a POST request the only difference is that the browser uses the response from the forms POST request to load the new page where as the AJAX requests response is passed to a callback in JavaScript.



Answered By - dangee1705
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I modify the XMLHttpRequest responsetext received by another function?

 September 06, 2022     ajax, javascript, monkeypatching, xmlhttprequest     No comments   

Issue

I am trying to modify the responseText received by a function that I cannot modify. This function creates a XMLHttpRequest that I can attach to, but I have been unable to "wrap" the responseText in a way that allows me to modify the content before the original function receives it.

Here's the full original function:

function Mj(a, b, c, d, e) {
    function k() {
        4 == (m && 'readyState' in m ? m.readyState : 0) && b && ff(b) (m)
    }
    var m = new XMLHttpRequest;
    'onloadend' in m ? m.addEventListener('loadend', k, !1)  : m.onreadystatechange = k;
    c = ('GET').toUpperCase();
    d = d || '';
    m.open(c, a, !0);
    m.send(d);
    return m
}
function ff(a) {
    return a && window ? function () {
        try {
            return a.apply(this, arguments)
        } catch(b) {
            throw jf(b),
                b;
        }
    } : a
}

I have also tried to manipulate the reiceiving function k(); in an attempt to reach my goal, but since it doesn't depend on any data passing to the function (for example k(a.responseText);) I had no success.

Is there any way that I can achieve this? I do not wish to use js libraries (such as jQuery);


EDIT: I understand that I cannot change .responseText directly since it is read-only, but I am trying to find a way to change the content between the response and receiving function.


EDIT2: Added below one of the methods I have tried to intercept and change .responseText which has been addapted from here: Monkey patch XMLHTTPRequest.onreadystatechange

(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
    if(/results/.test(url)) {
      console.log(this.onreadystatechange);
        this.addEventListener("readystatechange", function () {
            console.log('readystate: ' + this.readyState);
            if(this.responseText !== '') {
                this.responseText = this.responseText.split('&')[0];
            }
        }, false);
    }
    open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);

EDIT3: I forgot to include that the functions Mj and ff are not globally available, they are both contained inside an anonymous function (function(){functions are here})();


EDIT4: I have changed the accepted answer because AmmarCSE's does not have any of the problems and complexity linked to jfriend00's answer.

The best answer explained in short is as follows:

Listen to whichever request you want to modify (make sure your listener will intercept it before the original function destination does, otherwise there is no point in modifying it after the response has already been used).

Save the original response (if you want to modify it) in a temporary variable

Change the property you want to modify to "writable: true", it will erase whichever value it had. In my case I use

Object.defineProperty(event, 'responseText', {
    writable: true
});

Where event is the object returned by listening to the load or readystatechange event of the xhr request

Now you can set anything you want for your response, if all you wanted was to modify the original response then you can use that data from your temporary variable and then save the modifications in the response.


Solution

One very simple workaround is to change the property descriptor for responseText itself

Object.defineProperty(wrapped, 'responseText', {
     writable: true
});

So, you can extend XMLHttpRequest like

(function(proxied) {
    XMLHttpRequest = function() {
        //cannot use apply directly since we want a 'new' version
        var wrapped = new(Function.prototype.bind.apply(proxied, arguments));

        Object.defineProperty(wrapped, 'responseText', {
            writable: true
        });

        return wrapped;
    };
})(XMLHttpRequest);

Demo



Answered By - AmmarCSE
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check if the request is an AJAX request with PHP

 September 06, 2022     ajax, php, xmlhttprequest     No comments   

Issue

I would like to check server-side if a request to my php page is an ajax request or not.

I saw two ways to do this:

First way: sending a GET parameter in the request which tells the page that this is an AJAX request (=mypage.php?ajax)

mypage.php:

if(isset($_GET['ajax'])) {
    //this is an ajax request, process data here.
}

Second way: set a header to the xmlHttpRequest:

client-side js:

xmlHttpRequestObject.open(“GET”,url,true);
xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

mypage.php:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
    //request is ajax
}

The fact is, those two ways of doing it can easily be hacked, so it's not secure to check if i get an AJAX request like this.

How can i check if i'm receiving an AJAX request?


Solution

There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.



Answered By - Wayne Whitty
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 23, 2022

[FIXED] How can I open a JSON file in JavaScript without jQuery?

 July 23, 2022     javascript, json, xmlhttprequest     No comments   

Issue

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.

How can I get the contains of this JSON file in an object in JavaScript?

This is for example my JSON file located at ../json/main.json:

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}

and i want to use it in my table.js file like this:

for (var i in mainStore)
{       
    document.write('<tr class="columnHeaders">');
    document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
    document.write('<td >'+ mainStore[i]['description'] + '</td>');
    document.write('</tr>');
} 

Solution

Here's an example that doesn't require jQuery:

function loadJSON(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

Call it as:

loadJSON('my-file.json',
         function(data) { console.log(data); },
         function(xhr) { console.error(xhr); }
);


Answered By - Drew Noakes
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, April 16, 2022

[FIXED] How to set iframe content of a react component

 April 16, 2022     iframe, javascript, reactjs, xmlhttprequest     No comments   

Issue

I am trying to set the content of an iframe in a React component but I am not able to do it. I have a component that contains a function which has to be called when the iframe finishes loading. In that function I am setting the content but it doesn't seem like the onload function is called at all. I am testing it in the Chrome browser. I am trying the following:

var MyIframe = React.createClass({
    componentDidMount : function(){
        var iframe = this.refs.iframe.getDOMNode();
        if(iframe.attachEvent){
            iframe.attacheEvent("onload", this.props.onLoad);
        }else{
            iframe.onload = this.props.onLoad;
        }
    },
    render: function(){
        return <iframe ref="iframe" {...this.props}/>;
    }
});

var Display = React.createClass({
    getInitialState : function(){
        return {
            oasData : ""
        };
    },
    iframeOnLoad : function(){
        var iframe = this.refs.bannerIframe;
        iframe.contentDocument.open();
        iframe.contentDocument.write(['<head></head><style>body {margin: 0; overflow: hidden;display:inline-block;} html{ margin: 0 auto; text-align: center;} body > a > img {max-width: 100%; height: inherit;}', extraCss, '</style></head><body>', this.state.oasData.Ad[0].Text, '</body>'].join(''));
        iframe.contentDocument.close();
    },
    setOasData : function(data){
        this.setState({
            oasData : JSON.parse(data)
        });
    },
    componentDidMount : function(){
        var url = "getJsonDataUrl";

        var xhttp = new XMLHttpRequest();
        var changeOasDataFunction = this.setOasData;
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                changeOasDataFunction(xhttp.responseText);
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    },
    render : function(){
        return (
            <MyIframe refs="bannerIframe" onLoad={this.iframeOnLoad} />
        );
    }
});

module.exports = Display;

What am I doing wrong?


Solution

TLDR;

Edit react-iframe-examples

If you're looking for a way to control the contents of an <iframe> via React in a de-facto canonical way, Portals are the way to go. And as with all things Portal: Once you establish a reference to an existing and mounted DOM node (in this case that would be the contentWindow of a given <iframe>) and create a Portal with it, its contents are also considered children of the «parent» virtual DOM, which means a shared (synthetic) event system, contexts and so on.

Please note that, for code brevity, the examples below make use of the Optional chaining operator, which as of this writing is not supported in all browsers.

Example: A functional React component including hooks:

// iframe.js

import React, { useState } from 'react'
import { createPortal } from 'react-dom'

export const IFrame = ({
  children,
  ...props
}) => {
  const [contentRef, setContentRef] = useState(null)
  const mountNode =
    contentRef?.contentWindow?.document?.body

  return (
    <iframe {...props} ref={setContentRef}>
      {mountNode && createPortal(children, mountNode)}
    </iframe>
  )
}

Example: A React class component:

// iframe.js

import React, { Component } from 'react'
import { createPortal } from 'react-dom'

export class IFrame extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mountNode: null
    }
    this.setContentRef = (contentRef) => {
      this.setState({
        mountNode: contentRef?.contentWindow?.document?.body
      })
    }
  }

  render() {
    const { children, ...props } = this.props
    const { mountNode } = this.state
    return (
      <iframe
        {...props}
        ref={this.setContentRef}
      >
        {mountNode && createPortal(children, mountNode)}
      </iframe>
    )
  }
}

Usage:

import { IFrame } from './iframe'

const MyComp = () => (
    <IFrame>
        <h1>Hello Content!</h1>
    </IFrame>
)

Further control, for example over an <iframe>s <head> contents, can easily be achieved as this Gist shows.

There is also react-frame-component, a package that imho offers pretty much everything you need when working with controlled <iframe>s in React.

Caveats:

  • This answer only addresses use cases, where the owner of a given <iframe> wants to programmatically control (as in deciding about) its contents in a React-ish way.
  • This answer assumes, that the owner of an <iframe> complies with the Same-origin policy.
  • This answer is not suited to track how and when external resources are loaded in an <iframe src="https://www.openpgp.org/> kind of scenario.
  • If accessibility is something you care about, you should give your iframes meaningful title attributes.

Use cases (that I know of);

  • The OP's use case: Ads and the need to control how and when those can access a safely scoped element on your website.
  • Embeddable third-party widgets.
  • My use case (and hence my somewhat informed stance on the matter): CMS UI's, where you want to enable users to preview scoped CSS styles, including applied media queries.

Adding a given set of CSS styles (or stylesheets) to a controlled <iframe>:

As one comment author pointed out, managing styles between a parent application and the contents of a controlled <iframe> can be quite tricky. If you're lucky enough to have (a) dedicated CSS file(s) incorporating all necessary visual instructions for your <iframe>, it might suffice to just pass your IFrame component a <link> tag referencing said style(s), even though this is not the most standard compliant way to go about <link>refs:

const MyComp = () => (
  <Frame>
    <link rel="stylesheet" href="my-bundle.css">
    <h1>Hello Content!</h1>
  </Frame>
) 

In this day and age, however, and especially in a React world, most of the time, build setups create styles and stylesheets on the fly: Because they leverage meta-languages like SASS or even more involved solutions like CSS-in-JS stuff (styled-components, emotion).

This sandbox contains examples of how to integrate some of the more popular styling strategies with iframes in React.

Edit react-iframe-examples

This answer used to also give recipes with regards to versions of React prior to 16.3. At this point in time, however, I think it's safe to say that most of us are able to pull off a React version including Portals, and, to a lesser extent, hooks. If you're in need of solutions with regards to iframes and React versions < 16, hit me up, I'll gladly offer advice.



Answered By - Lukas Bünger
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing