Open new window without URL. PHP/JavaScript - javascript

The problem currently:
I have a website that we are moving to a mobile application so I have put the website inside an IFrame (this has to be done not my choice). However when you click a certain link on the website (ON MOBILE) it will take you to a third party website or download page still inside the original Iframe. This is where the problem arises when you are on that third party website or download page there is no back button for mobile users (ios specifically).
My Ideas:
One way to fix this problem would be if the button is clicked the contents open up in a new window outside of the original Iframe on mobile.
Once the buy now button is clicked you will get directed to the third party website link.
This buttons code is not written in simple html or css though so there is no basic url set to the button. This means the window.open function will not work since a url is required and putting "_blank" attribute inside the php variable did not work either. Since my button is in a PHP variable called button that triggers a dynamic url through a CMS I am quite lost and not sure if this can be done.
What I want to happen is a new window to open with the third party website outside of the IFrame.
My PHP button
$button .= "<button class=\"btn btn-product-box get-coupon-btn deal-download ".$extraClass."\" onclick=\"myFunction()" . "\" data-action=\"".$purchaseAction."\">".$text."</button>";
I believe that the data-action attribute which holds the value $purchaseAction is related to the urls or links
I have added an onclick function to the button called myFunction which is a java script function that I am trying to write to trigger the button to open its contents in a new window.
My onclick function
function myFunction() {
document.getElementsByClassName('get-coupon-btn');
console.log("clicked myFunction");
var jsvar = '<?=$purchaseMethod?>';
console.log(jsvar);
}
I believe that $purchaseAction holds the URLs to the third party websites. But since they are grabbed from a CMS through twig programming language I do not have the http links for the sites and the button will trigger a different website depending on what button is clicked.
Here is more of the code
$purchaseMethods = $purchasable->purchaseMethods->orderBy(new Expression("Field(`typeId`, 32,18,19,31,17)"))->all();
// Log::error_log($purchasable->purchaseMethods->orderBy(new Expression("Field(`typeId`, 32,18,19,31,17)"))->getRawSql());
// $totalBtn = 0;
if(empty($purchaseMethods)){
$text = "REPORT ERROR";
if($short){
$text = "ERROR";
}
$button = "".$text."";
}
foreach($purchaseMethods as $loopIndex => $purchaseMethod){
switch ($purchaseMethod->type){
case "printMaterial":
$purchaseAction = $purchaseMethod->image->count() != 0? $purchaseMethod->image->one()->url : null;
$text = "GET COUPON";
if($short){
$text = "GET";
}
//$button .= "<button class=\"btn btn-product-box get-coupon-btn deal-download ".$extraClass."\" data-action=\"".$purchaseAction."\">".$text."</button>";
$button .= "<button class=\"btn btn-product-box get-coupon-btn deal-download ".$extraClass."\" onclick=\"myFunction()"."\" target=\"_blank" ."\" data-action=\"".$purchaseAction."\">".$text."</button>";
?>
<script>
//const { shell } = require('electron');
//var aHref = document.querySelector('#aHref');
function myFunction() {
document.getElementsByClassName('get-coupon-btn');
console.log("clicked myFunction");
//var jsvar = '<?=$purchaseMethod?>';
//console.log(jsvar);
}
</script>
Is there any way I can get the button to open its contents in a new window without using window.open or _blank since they both require urls?

You are calling myFunction(), when the button is clicked in Iframe.
Inside myFunction, you can open the URL using the following code which will open URL in a new tab outside Iframe
window.open(href, '_blank');
Here href is URL which you are grabbing from HTML

Related

PHP session changing after a new window returns to my site from third party site

I have a PHP website www.example.com which has a button opening a new window with JS. It then loads a unique url to www.thirdpartywebsite.com via AJAX and sets the window's url:
var newWindow = window.open("", "_blank", "scrollbars=yes,resizable=yes");
ajax("www.example.com/get-url",
{
data: someData,
success: function(response)
{
newWindow.location = response.url;
// something like www.thirdpartywebsite.com/catalog/12345xyz
}
});
Backend PHP code for www.example.com/get-url simply makes a curl request to www.thirdpartywebsite.com for the unique url and then returns it.
The returned third party site url is a page showing a catalog of items. Each item has a button redirecting the user back to my site with the item data in POST. The url for that is www.example.com/get-data with the following PHP code:
$itemData = $_POST["data"];
echo '<div id="content-json" style="display:none;">' . json_encode($itemData) . '</div>';
echo '<script>';
echo 'var json = document.getElementById("content-json").innerHTML;';
echo 'var data = JSON.parse(json);';
echo 'window.opener.returnCallback(data);';
echo 'window.close();';
echo "</script>';
The returnCallback function is on the same page (main window) as the button opening the new window:
function returnCallback(data)
{
// Set page's content with data
// ...
}
So basically we open a new window to other site, user does action, the new window redirects back to my site with POST data, gives the data to the main window as JS object and then closes the new window.
Now the problem is that the PHP session id gets regenerated when the new window is redirected back to my site. I have confirmed this with typing document.cookie into the main window's console.
Before clicking the button to open the new window and before clicking the button on the new window to redirect back to my site:
PHPSESSID=random12345
After redirecting back to my site and the new window closes:
PHPSESSID=random67890
What is even more interesting is that this doesn't happen every time and not with every user. It sometimes happens on one day on one browser with one user and then some other day/time it doesn't.
The only thing I can come up is if the domain changes between www.example.com and example.com but it's always https://www.example.com.
Anyone know any reason why this would happen?

Open a new page with div contents

I have some hidden divs in a HTML page with specific IDs:
<div id='log1' style='visibility: hidden;display: none;'>content</div>
<div id='log2' style='visibility: hidden;display: none;'>content</div>
And then some links:
<a href='?' target='_blank'>Log 1</a>
<a href='?' target='_blank'>Log 2</a>
I want the browser to open a new page / tab (or even a popup but this might be bad if the user has popup blockers) with the contents of the corresponding div.
I know I could do some Javascript to create a floating div and show the data in the same page, but I'd like to avoid that. Moreover, if there is a way of doing what I ask without JS (which I doubt) even better.
You can't do a popup based on hidden divs in your HTML without using JavaScript, no. There's a CSS trick where if you put the divs far off the page and give them an ID, then link to that as an anchor, the browser will scroll it into view.
On the JavaScript side, it's fairly straightforward. First, add a data-log attribute to them to tell us what log we should show, then:
var links = document.querySelectorAll("...some selectors for your links...");
Array.prototype.forEach.call(links, function(link) {
link.onclick = function() {
var log = document.getElementById(this.getAttribute("data-log"));
var wnd = window.open("", "_blank");
wnd.document.write(
"<!doctype html>" +
"<html><head>" +
"<meta charset='appropriate charset here'>" +
"<title>Title here</title>" +
"</head><body>" +
"<div>" + log.innerHTML + "</div>" +
"</body></html>"
);
wnd.document.close();
return false; // Prevents the default action of following the link
};
});
Note the window.open must be done within the click handler; most popup blockers will allow the popup if it's in direct response to a user action.
window.open returns a reference to the window, and then we can write to its document.
(I don't normally use onclick handlers, but you didn't mention using any library and there's still a lot of IE8 out there. Using onclick lets us use return false to prevent the default; details in this small article on my anemic little blog.)
var newWindow = window.open("about:blank", "", "_blank");
newWindow.document.write(html);
In this case you should be doing this using javascript within a call back it could be on page load or on button click or something else

How to set the title for the new browser tab?

I have a question about the new tab for the link.
Is there anyway I can set the browser tab title before user clicks a link? It seems like there is no way to debate the title for the new tab if the html contained in the new tab doesn't have title attribute. Am I right? How do I set the title?
//the href is dynamic so I can't set them one by one because I have 100+ html file here
<a href="test.html" target="_blank">open me<a>
As you have it, this is not possible because your links are just normal HTML links. When the new page opens in a new tab, the current page will not have any reference to it and so cannot change it in any way. You will need to open the page using javascript and set the title that way.
You can dynamically set this up in window onload to find all a tags and add a click event whihc opens the window and sets the title.
If you want different titles for each page, you can store this in a data- attribute in the a tag.
Note tho that this will only work with pages in the same domain (for security), and that it does not handle people right clicking and pressing "Open in New Window". Middle click in Windows does seem to work however.
HTML
open me
JavaScript
window.addEventListener("load", function() {
// does the actual opening
function openWindow(event) {
event = event || window.event;
// find the url and title to set
var href = this.getAttribute("href");
var newTitle = this.getAttribute("data-title");
// or if you work the title out some other way...
// var newTitle = "Some constant string";
// open the window
var newWin = window.open(href, "_blank");
// add a load listener to the window so that the title gets changed on page load
newWin.addEventListener("load", function() {
newWin.document.title = newTitle;
});
// stop the default `a` link or you will get 2 new windows!
event.returnValue = false;
}
// find all a tags opening in a new window
var links = document.querySelectorAll("a[target=_blank][data-title]");
// or this if you don't want to store custom titles with each link
//var links = document.querySelectorAll("a[target=_blank]");
// add a click event for each so we can do our own thing
for(var i = 0; i < links.length; i++) {
links[i].addEventListener("click", openWindow.bind(links[i]));
}
});
Sample JsFiddle
You can pass the title with hash and get it on another page, if this another page is yours and you can modify its code.
1st page:
...
<a href="test.html#the_title_you_want" target="_blank">open me<a>
...
2nd page - modify the body opening tag like this:
<body onload="document.title=window.location.hash.replace('#','');">
If the page you are linking to isn't yours, you can use window.open method:
open me
I have not seen addEventListener work reliably, especially when opening a new page using javascript. The best way to change the tab title and have it work reliably is to set a timeout until the page loads. You may have to play with the timeout value, but it works.
var newWindow = window.open(url, '_blank');
setTimeout(function () {
newWindow.document.title = "My Tab Name";
}, 100);
You have two options. Using pure HTML, you can let the user open up links, then later on change the title. Or you can change the title with inline JavaScript. Here's how you do both:
Method 1
Change your links by assigning a target attribute, and then later on use that window name to control the document. For instance in your links it would be: <a href="whatever" target="theNewWindow">. Whenever you want to change the title for this page, you'd use JavaScript as such: window.open("", "theNewWindow").document.title = "New Page Title!"; The problem with this method however is that all links with that target/window name will open in that same window. In addition, after the first time the link is clicked, your browser won't automatically switch to the new tab/window.
Method 2
Change your links by assigning an onclick attribute, which would open the link manually and change the title of the page immediately. Basically it would come down to look like: <a href="whatever" onclick="var w=window.open(this.href, '_blank'); (w.onload=function(){w.document.title='New Page Title!';})(); return false;">. This opens the window based on the href attribute, immediately changes the title, and sets the window to change the title to that when it finishes loading (just in case there really was a title tag).
The problem with both of these methods (as mentioned by others) is your html files have to be on the same domain.
The simplest way is a follows:
var winTab = window.open("", "_blank")
//Open URL by writing iframe with given URL
winTab.document.write("write iframe with your url in src here")
//Set Title for the new tab
winTab.document.title = "Form Title"
You could make your own Page 2 that opens up the other pages (the ones you can't edit), in a frameset. You can then either change the title dynamically when loading your page 2, or as others have suggested if you use window.open you can control the title from the parent page.
If you are in page 1, and opening page 2 in a new tab, you can't set title for page 2 from page 1.
If you have access to page 2 then it's possible, otherwise not.

Javascript: Clicking Link to Download pdf

I am working on a JS program which should open a webpage www.mysite.com & click on a link inside that webpage to download a pdf.
The link to click looks like this:
<a onclick="download();return false;" href="#noWhere">Click to Download</a>
Ordinarily, manually clicking the link, calls the following function to download the pdf:
function download() {
document.forms[0].action = path + "/xxW04_sv_0140Action.do";
document.forms[0].target = "_self";
document.forms[0].submit();
}
My code is simplified javascript code to open the page & click on the "Click to Download" button is this:
<script>
var linkname = "http://www.mysite.com";
var windowname = "window_1"
// Opens a new window
var myWindow = window.open(linkname, windowname ,"width=400,height=600");
//should open a link to download pdf
myWindow.document.getElementById('href = \"#noWhere\"').click();
</script>
So far I can open the webpage "mysite.com" in a seperate window using but for some reason no button clicking is happening and certainly no pdf is downloaded.
Of course if I manually click the "Click to Download" button it downloads.
Can anyone tell me what i'm doing wrong? Why I cannot simulate a click with the above js code?
Or possibly give me some things to try. Any help much appreciated and Than you.
UPDATE:
From the initial answers below, possibly this method is doomed for failure! Can anyone suggest a better way I could be downloading these pdfs?
You'd better use:
<a href="http://www.mysite.com/mypdf.pdf">
This should download that pdf file.
It won't work. The same-origin policy will prevent you from accessing the content of any pages loaded from another domain.
Also, as #kamilkp pointed out, you have to provide the getElementById() function with an id value. You can't just plug any old stuff in there and expect it to work.
Another problem is your reliance on clicks for this to work. What about users that use the tab key to select links and then press Enter to follow the link?

javascript generated links not working in ie8

there is a problem in ie8 related to links. html generated from javascript and display in the jquery ui dialog box but when I click on the link in it, it open link url in the same window (a tag has the targer=_blank set) and the url of link appended to the host url.
var clip_link = 'http://www.example.com/'+'c/'+id;
var thumb = 'http://www.example.com/235/45'+'/thumb.jpg';
$('#clip-share-popup .thumb').append(
'<img src="'+thumb+'" alt="clip thumb" />'
);
it is set after an ajax call
page url is
http://www.example.com/abcd.php#page/1/1
after click on the link the url become
http://www.example.comhttp//www.example.com/c/1234#
this doesn't happen in any other browser
You are probably not prefixing links with http://:
Google
Would take you to http://www.yourwebsite.com/whatever-page-you-are-on/www.google.com

Categories