React, loading a script inside a form (mercadopago) - javascript

I am trying to implement some payment system (MercadoPago).
According to the doc, it's just pasting this:
<form method="POST">
<script
src="https://www.mercadopago.com.pe/integrations/v1/web-payment-checkout.js"
data-preference-id="589788715-2e52aeec-8275-487c-88ee-1a08cff37c08"
></script>
</form>
Pasting it in a pure html file works fine: a button appears and clicking it opens a modal to pay with a credit card as expected. However this doesn't work in React since it's dynamically loading a script. Hence, I tried using an effect hook to insert the <script> on load as such:
const App = () => {
const setMercadoPagoPreferences = async () => {
const script = document.createElement('script');
script.src =
'https://www.mercadopago.com.ar/integrations/v1/web-payment-checkout.js';
script.async = true; // commenting or uncommenting seems to have no effect
script.setAttribute(
'data-preference-id',
'589788715-2e52aeec-8275-487c-88ee-1a08cff37c08'
);
document.getElementById('mercadoForm').appendChild(script);
};
useEffect(() => {
setMercadoPagoPreferences();
}, []);
return <form action='/procesar-pago' method='POST' id='mercadoForm' />;
};
This loads correctly the script, it seems, as a button to pay is appended to the page. Clicking it however opens a modal that says "oh no, something bad happened". This doesn't happen on my .html example above; so it must be because of how React is loading the script or something like that. It doesn't work on either the dev or the production build.
Edit: As suggested, I tried using refs instead of directly appending childs but this did not seem to have any impact, it still won't work.

I dont know this framework but maybe thats the way: It looks like this guy has similar problem right here.
I think there is problem because script does not load on time. So maybe lets try this:
script.onload = () => {
document.getElementById('mercadoForm').appendChild(script);
};
In addtion there is build in mechanism in react ref like HERE instead of document.getElementById

Your technique would've work if it weren't for mercadolibre.
Apparently, the use of the page you are trying to load is not allowed by mercadolibre. It's like you're trying to load mercadolibre inside an Iframe which they probably blocked using CSP header. Specifically they are setting the Content-Security-Policy tag to frame-ancestors 'self'. It's a security restriction standard that does not allow the use of pages from that domain within elements Iframe.

Related

Lazy-load a javascript script?

Is there a way I can wrap an external JS script embed with lazy-load behavior to only execute when the embed is in the viewport?
Context: I have an external javascript embed that when run, generates an iframe with a scheduling widget. Works pretty well, except that when the script executes, it steals focus and scrolls you down to the widget when it’s done executing. The vendor has been looking at a fix for a couple weeks, but it’s messing up my pages. I otherwise like the vendor.
Javascript embed call:
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js> </script> <script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
While I'm waiting for the vendor to fix their js, I wondered if lazy-loading the JS embed may practically eliminate the poor user experience. Warning: I'm a JS/webdev noob, so probably can't do anything complicated. A timer-based workaround is not ideal because users may still be looking at other parts of the page when the timer runs out. Here are the things I’ve tried and what happens:
I tried:
What happened:
Add async to one or both of the script declarations above
Either only shows the link or keeps stealing focus.
Adding type=”module” to one or both script declarations above
Only rendered the link.
Wrapping the above code in an iframe with the appropriate lazy-loading tags
When I tried, it rendered a blank space.
Also, I realize it's basically the same question as this, but it didn't get any workable answers.
I actually also speak french but I'll reply in english for everybody.
Your question was quite interesting because I also wanted to try out some lazy loading so I had a play on Codepen with your example (using your booking id).
I used the appear.js library because I didn't really want to spend time trying some other APIs (perhaps lighter so to take in consideration).
The main JS part I wrote is like this:
// The code to init the appear.js lib and add our logic for the booking links.
(function(){
// Perhaps these constants could be put in the generated HTML. I don't really know
// where they come from but they seem to be related to an account.
const VENDOR_LIB_SRC = "https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js";
const UUID = "871dab0c-4011-4293-bee3-7aabab857cfd";
const SERVICE = 1158717;
let vendorLibLoaded = false; // Just to avoid loading several times the vendor's lib.
appear({
elements: function() {
return document.querySelectorAll('a.booking-link');
},
appear: function(bookingLink) {
console.log('booking link is visible', bookingLink);
/**
* A function which we'll be able to execute once the vendor's
* script has been loaded or later when we see other booking links
* in the page.
*/
function initBookingLink(bookingLink) {
window.TTE.init({
targetDivId: bookingLink.getAttribute('id'),
uuid: UUID,
service: SERVICE
});
}
if (!vendorLibLoaded) {
// Load the vendor's JS and once it's loaded then init the link.
let script = document.createElement('script');
script.onload = function() {
vendorLibLoaded = true;
initBookingLink(bookingLink);
};
script.src = VENDOR_LIB_SRC;
document.head.appendChild(script);
} else {
initBookingLink(bookingLink);
}
},
reappear: false
});
})();
I let you try my codepen here: https://codepen.io/patacra/pen/gOmaKev?editors=1111
Tell me when to delete it if it contains sensitive data!
Kind regards,
Patrick
This method will Lazy Load HTML Elements only when it is visible to User, If the Element is not scrolled into viewport it will not be loaded, it works like Lazy Loading an Image.
Add LazyHTML script to Head.
<script async src="https://cdn.jsdelivr.net/npm/lazyhtml#1.0.0/dist/lazyhtml.min.js" crossorigin="anonymous" debug></script>
Wrap Element in LazyHTML Wrapper.
<div class="lazyhtml" data-lazyhtml onvisible>
<script type="text/lazyhtml">
<!--
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js>
</script>
<script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
-->
</script>
</div>

How do I import html into another html document?

I'm trying to keep my nav in one html file rather than copying and pasting it into every file so I don't have to edit every file if I want to change something. I want to include the nav code into my files but nothing I've tried so far has worked the way I want it to. I would like to do this using only html/css/js, this is something that seems like there would be an easy way to do it because it's so practical in a lot of projects.
So far I've tried
object/iframe - Embedded the code into it's mini window, not the desired result.
javascript object.write - Deleted code already in file being imported to.
w3.includehtml - Works in firefox, but not chrome, I can't figure out why. Help with this would be appreciated as this seems like the best method.
php include- Didn't work, probably because I don't know php and most likely did something wrong, I'm open to it if someone could show me how or link a tutorial.
create the component as a template, like:
nav.template.html
<template>
<nav><!-- nav stuff here ... there has to be only one childNode of template because of how we will mount it, but you could change that -->
<style scoped>/* you can style only nav content directly here if you like */</style>
</nav>
</template>
Then, load that with javascript on domready, like:
site.js
document.addEventListener('DOMContentLoaded', function() { // there are more thorough, extensible ways of attaching to this event ..
let el = document.querySelector('.nav-mount-point')
// I'm doing to use axois, assuming you load it from a CDN or directly. You could also do this with plain AJAX, etc
axios.get('path/to/nav.template.html')
.then(res => {
let dt = document.createElement('div')
dt.innerHTML = res.data
el.appendChild(dt.children[0].content.cloneNode(true))
})
.catch(e => console.error(e))
}, false);

ReactJS - How to render iframe inner contents server-side, for SEO?

I'm working on an application which supports both client and server-side rendering using Facebook's React JS framework.
I need to render an iframe, which has some html inside of it. The HTML is created using a script that I have access to.
However, I want the inner content to be rendered on the server, so that the HTML shows up in search engines. The problem is that for the inner content to be created, it normally needs to wait for the iframe to 'load', which does not happen on the server.
How can I do this?
Here's what I tried, which doesn't work:
render: function() {
return (
<div>
<iframe
ref="myIframe">
</iframe>
</div>
);
},
componentDidMount : function() {
var iFrameNode = this.refs.myIframe,
frameDoc = iFrameNode.contentWindow.document;
frameDoc.write('<html><body style="margin:0px;"><div><script type="text/javascript" src="..."></script></div> ... more html');
}
Note that I'm adding the content on componentDidMount because otherwise it gets 'erased' when the iframe loads.
A good way to do it is to use data URI scheme. It allows inserting html content to an iframe via the src attribute.
Currently supported on all browsers except IE (partial support - no html option) - caniuse.
This will allow google search engine to read the content of the iframe on the server side.
So your code should be -
render: function() {
var frameSrc = browser.ie ? '' : 'data:text/html,<html><body style="margin:0px;">...more html">'
return (
<div>
<iframe
ref="myIframe"
src="{frameSrc}"
</iframe>
</div>
);
},
componentDidMount : function() {
if (browser.ie) { //some browser detection library/code
var iFrameNode = this.refs.myIframe,
frameDoc = iFrameNode.contentWindow.document;
frameDoc.write('<html><body style="margin:0px;"><div><script type="text/javascript" src="..."></script></div> ... more html');
}
}
IFrames are sometimes used to display content on web pages. Content
displayed via iFrames may not be indexed and available to appear in
Google's search results. We recommend that you avoid the use of
iFrames to display content. If you do include iFrames, make sure to
provide additional text-based links to the content they display, so
that Googlebot can crawl and index this content.
- Google Webmaster Guidelines
So from a SEO standpoint, you either need to stop using iframes here or accept that it won't be indexed.
Clever tricks like putting it in the html, and then switching it to an iframe won't help because Googlebot uses JavaScript... unless you do useragent sniffing to send empty JavaScript files, but I don't recommend that.
The direct answer is to use __dangerouslySetInnerHTML if !this.state.x, and in componentDidMount setTimeout(() => this.setState({x: true}), 0), and inject the html into the iframe in componentDidUpdate.
There is a React component to render iframes: https://github.com/svenanders/react-iframe
You can get it with npm install react-iframe, then use it like this in your React code:
import React from 'react';
import Iframe from 'react-iframe';
...
// In your render function:
<Iframe url="whatever.html" />
Unfortunately for me, I would actually prefer to render my server-generated HTML into a <div> rather than an actual <iframe>...

Trying to load an API and a JS file dynamically

I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks

JQuery load() will break facebook like button/comment box. How to workaround?

I am coding a big website but I have cut down my problem into the following tiny html file:
http://dl.dropbox.com/u/3224566/test.html
The problem is that if I (re)load with JQuery a content that features a facebook code, the latter won't appear, even if I reload the script (leading to a duplication of that all.js script, which is another issue).
How can I fix this?
Regards,
Quentin
Use the FB.XFBML.parse() docs after you load the new content
function loadPage() {
$('#test').load('test.html #test', function() {
FB.XFBML.parse( );
}).fadeOut('slow').fadeIn('slow');
}
Note, that loading a fragment with id test in a div with id test will create multiple (two) elements with the same id (nested in each other) in the page, which should never happen as it is invalid.
To avoid this use the more verbose $.get method
$.get('test.html',
function(data) {
var temp = $('<div>').html(data).find('#test');
$('#test').html(temp.html());
}
);

Categories