Breaking out of iframes with Javascript - javascript

Edit (rephrasing): the website is loaded within an iframe, but there is 1 link inside the iframe which I would like to take the user out of the iframe when they click it, back into the main window that underlays the iframe.
I've found
top.location.href = 'page.htm';
, but I wouldn't know how to enter it into this 'complex' code.
This is the file I believe it should be in:
{literal}
$(document).ready( function() {
$('#payment_paypal_express_checkout').click(function() {
$('#paypal_payment_form').submit();
return false;
});
$('#paypal_payment_form').live('submit', function() {
var nb = $('#quantity_wanted').val();
var id = $('#idCombination').val();
$('#paypal_payment_form input[name=quantity]').val(nb);
$('#paypal_payment_form input[name=id_p_attr]').val(id);
});
function displayExpressCheckoutShortcut() {
var id_product = $('input[name="id_product"]').val();
var id_product_attribute = $('input[name="id_product_attribute"]').val();
$.ajax({
type: "GET",
url: baseDir+'/modules/paypal/express_checkout/ajax.php',
data: { get_qty: "1", id_product: id_product, id_product_attribute: id_product_attribute },
cache: false,
success: function(result) {
if (result == '1') {
$('#container_express_checkout').slideDown();
} else {
$('#container_express_checkout').slideUp();
}
return true;
}
});
}
$('select[name^="group_"]').change(function () {
displayExpressCheckoutShortcut();
});
$('.color_pick').click(function () {
displayExpressCheckoutShortcut();
});
{/literal}
{if isset($paypal_authorization)}
{literal}
/* 1.5 One page checkout*/
var qty = $('.qty-field.cart_quantity_input').val();
$('.qty-field.cart_quantity_input').after(qty);
$('.qty-field.cart_quantity_input, .cart_total_bar, .cart_quantity_delete, #cart_voucher *').remove();
var br = $('.cart > a').prev();
br.prev().remove();
br.remove();
$('.cart.ui-content > a').remove();
var gift_fieldset = $('#gift_div').prev();
var gift_title = gift_fieldset.prev();
$('#gift_div, #gift_mobile_div').remove();
gift_fieldset.remove();
gift_title.remove();
{/literal}
{/if}
{if isset($paypal_confirmation)}
{literal}
$('#container_express_checkout').hide();
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
{/literal}
{else if isset($paypal_order_opc)}
{literal}
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
{/literal}
{/if}
{literal}
var modulePath = 'modules/paypal';
var subFolder = '/integral_evolution';
var fullPath = baseDir + modulePath + subFolder;
var confirmTimer = false;
if ($('form[target="hss_iframe"]').length == 0) {
if ($('select[name^="group_"]').length > 0)
displayExpressCheckoutShortcut();
return false;
} else {
checkOrder();
}
function checkOrder() {
confirmTimer = setInterval(getOrdersCount, 1000);
}
{/literal}{if isset($id_cart)}{literal}
function getOrdersCount() {
$.get(
fullPath + '/confirm.php',
{ id_cart: '{/literal}{$id_cart}{literal}' },
function (data) {
if ((typeof(data) != 'undefined') && (data > 0)) {
clearInterval(confirmTimer);
window.location.replace(fullPath + '/submit.php?id_cart={/literal}{$id_cart}{literal}');
$('p.payment_module, p.cart_navigation').hide();
}
}
);
}
{/literal}{/if}{literal}
});
{/literal}
Edit: found some part of the HTML as well, figured it'd be easy to do there, but it doesnt actually seem to work. Perhaps because of the void(0)?
<a href="javascript:void(0)" target="_top" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'}">
Perhaps someone here can help me out. Thanks in advance!
Best,
Dave

This is some JavaScript that will redirect the user out of the iframe to the website if the website is being 'iframed':
<script>if (top !== self) top.location.href = self.location.href;</script>

I do not see a portion of the code for your form, but since you are using submit() you can set the target of the form to _top:
<form target="_top" action="yoururl.php" id="paypal_payment_form">
Then once you use submit, it will break the frames and continue to the new page.
<a href="#" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'>

Related

href not working in greasemokey

I have following code in my greasemonkey script. In case, i am unable to save my order to server, i display an error message and then a link (created using <a href> to save it again. this link is save_order method again. But this is not working. I tried debugging into it but no luck. (I have basic understanding of JavaScript)
function save_order() {
server_url = 'https://server.com/api/put_order?user_id=' + form.user.value +'&order_id=' + orderId;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200){
localstorage.removeItem(orderId);
messageBar.innerHTML += '<br/>Order has been saved successfully.';
} else {
if (errorBar.style.display === 'none'){
errorBar.style.display = 'block';
}
errorBar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}
=======
FULL CODE
// ==UserScript==
// #name SaveOrder
// #version 1.0
// #author myname
// #include https://xx*.xxxxxxxx.com*/*
// #run-at document-end
// #grant GM_xmlhttpRequest
// ==/UserScript==
var saveButton = document.getElementById('save-button');
saveButton.addEventListener("click", save_order,true);
var info_bar = document.getElementById('info_bar');
var error_bar = document.getElementById('error_bar');
var form = document.getElementById('place_order_form');
var order_id = form.order_id.value;
var localstorage = window.localStorage;
if (localstorage.getItem(order_id)){
save_to_db();
}
function save_order(){
localstorage.setItem(order_id, order_id);
}
function save_to_db() {
var random_boolean = false;//Math.random() >= 0.5;
console.log(random_boolean);
server_url = 'https://xxx.xxxx.com/api/put_order?user_id=' + form.user.value +'&order_id=' + order_id;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200 && random_boolean){
localstorage.removeItem(order_id);
info_bar.innerHTML += '<br/>Order saved successfully';
} else {
if (error_bar.style.display === 'none'){
error_bar.style.display = 'block';
}
error_bar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}
Your method works just fine, as you can see in this example.
You probably have an error elsewhere.
function test(){
document.body.innerHTML += '<a class="function-link" href="#" onclick="test();">Test</a>';
}
<a class="function-link" href="#" onclick="test();">Test</a>
EDIT : I did some digging, and found a way around your issue.
Instead of adding an onclick on your link, create an event handler in javascript attached to a save-to-db class like this :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
Now all you need to do is get rid of your onclick and replace it with class="save-to-db"
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
It works like a charm now :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
save_to_db();
function save_to_db() {
console.log('Function called');
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}

Ajax posting on localhost but not on VPS host

I've been facing this issue for many days i've searched the whole internet fixed my php.ini even the ngnix.confg file
Please tell me if anything is wrong with the code
i've edited the Cropper Plugin not to download but replace the current image.
so what i did i used the ajax post to do it.
PS: Ajax is sending huge data in post since it's a canvas and this whole process is working fine on localhost but not working on server. The whole site is on laravel but this code is on native php.
I've also figured out that if image is small then it's working fine and if image is large then it's not working on server.
AJAX code in main.js file
$('.docs-buttons').on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
console.log(e.message);
}
}
}
if (data.method === 'rotate') {
$image.cropper('clear');
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.method === 'rotate') {
$image.cropper('crop');
}
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
var temp = $(' #image').attr('src');
jQuery.ajax({
url: '../../cropper/demo/save.php',
type: 'POST',
data: {
data: result.toDataURL('image/jpeg'),
name: temp,
},
complete: function(data, status)
{
console.log(data.responseText);
if(status=='success')
{
$('#image').cropper("replace", temp);
}
else
{
alert('Error has been occurred');
}
}
});
}
break;
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
console.log(e.message);
}
}
}
});
save.php (To store the image on server)
<?php
$based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1);
$fileName='';
$fileName = substr($_POST['name'], 34);
$image = imagecreatefromstring(base64_decode($based64Image));
if($image != false)
{
if(!imagejpeg($image,"..\..\images\image\\".$fileName))
{
// fail;
}
}
else
{
// fail;
}
?>
Please Help Thanks
Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
For more details and understanding please read
https://gist.github.com/magnetikonline/11312172#determine-fastcgi-response-sizes
These results may not be accurate, so reading to ensure your proper configuration is advised

Prevent users from opening multiple instance of same website PHP

I need only one tab accessible for my website. When he tries to open in new tab or even tries to copy and paste the url in new tab should clear the user's session and logout from the application.
There are several reasons,
When a user opens a new tab connecting to the same application - the session id is the same.
Imagine that this user has reached a page X in the application flow from the first tab.
When he opens the second tab he might be in one of the following scenarios - depending how the second tab was opened - new tab, duplicate tab (this copies the URL to the newly opened tab), or new session.
All of the above will "confuse" the server as to what the next valid state of the application is, and could override data entered in different tab, without his/her knowledge
What I want is to prevent a single user to have several tabs in the same session, i.e. only one tab/window per user, per session.
Including the below script in dashboard.php after login
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
else
{
sessionStorage.pagecount = 1;
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
Below code in other sub pages in the application
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
</script>
Added the below script after I login(say dashboard.php)
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Added the below script in Header in rest of my pages - 'random_value' is from db for that user
<script>
$(document).ready(function()
{
$("a").attr("target", "_self");
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
if('<?=$random_value?>' == window.name)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>

Changing url using javascript and jquery

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Loading dynamically generated content and URL after page reload

I have a Google Instant style search script written in jQuery. When a user searches, a URL is created which is something like #search/QUERY/3/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be?
Here is my jQuery code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var page=1;
var yt_url='search.php?q='+query+'&category=web&d='+page+'';
window.location.hash='search/'+query+'/'+page+'/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("Your search did not return any results");
}
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
I think it could be something to do with these lines of code:
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
You need to write a function for the search so you can specify the page number.
$(document).ready(function(){
var search = function (query, page) {
page = page ? page : 1;
query = encodeURIComponent(query),
var yt_url = 'search.php?q=' + query + '&category=web&d=' + page + '';
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
} else {
window.location.hash = 'search/' + query + '/' + page + '/';
document.title = $(this).val() + " - My Search Script";
}
$.ajax({ ... });
};
$("#search").keyup(function(){ search(this.value); });
if (window.location.hash.indexOf('#search/') == 0) {
var query = window.location.hash.replace('#search/', ''),
page = query.replace(/.+?\/(\d+)\//, '$1');
query = query.replace(/\/\d+\//, '');
search(decodeURIComponent(query), page);
}
});

Categories