JavaScript popup url - javascript

How can i get url of a popup opened by JS.
Here is my code:
var _url = 'someurlhere';
var popupwindow = window.open(_url, "Popup", 'width=800, height=600');
var _this = this;
var pollTimer = window.setInterval(function() {
try {
console.log(popupwindow.document.URL);
} catch(e) {
console.log(e.message);
}
}, 500);
but I'm getting a Cannot read property 'URL' of undefined error on line with console.log(e.message). Why ?

It won't work because you are using a url that is a different domain than the page you are running the script on. This is a violation of the "same origin policy". IOW it is XSS, not allowed.

Use popupwindow.location.href instead popupwindow.document.URL

Related

window.open is dropping the = in my parameter list on my home page only

I'm calling javascript to append a parameter to my URL prior to calling window.open. This code works perfectly on every page but my homepage. On the homepage, the "=" is dropped in the parameter list. Any ideas why?
On every page but homepage, the window opens as expected:
https://dev.mysite.com/?m_=myModal0
On the homepage, the window opens like this:
https://dev.mysite.com/?m_myModal0
<?php esc_html_e('get code', 'comre');?>
<script>
function OpenModal(modalid){
var win;
//event.preventDefault();
if(window.location.href.indexOf("m_") > -1) {
var reexp = new RegExp(/m_=(.*?)$/);
var url = window.location.toString();
var newUrl = url.replace(reexp, ("m_=" + modalid));
win = window.open(newUrl, '_blank');
}
else {
if(window.location.href.indexOf("?") > -1) {
win = window.open(document.URL+"&m_="+modalid, '_blank');
}
else {
win = window.open(document.URL+"?m_="+modalid, '_blank');
}
}
win.focus();
return true;
}
</script>
There are no errors shown in the console.
Be nice to your users: don't force them to allow popups on your website by insisting on window.open. Instead, create a normal navigation link, and click that. So instead of this:
var url = window.location.toString();
...
window.open(url);
use this:
function openInNewTab(url) {
let a = document.createElement('a');
a.style.display = "none";
a.href = url;
a.target = "_blank";
document.body.appendChild(a);
a.click();
document.body..removeChild(a);
}
...
var url = ...
openInNewTab(url);
Is that more code? Sure, but it's a one-time function declaration so not something worth caring about: call . But it also means opening a URL like any other, with the browser doing everything it normally does when people navigate from page to page.

Post a message to newly opened browser

I'm trying to post a message using the postMessage function to a browser that I've opened using window.open and while I've found a couple of articles explaining on how to do it:
Window.postMessage()
HTML5’s window.postMessage API
I just can't get it to work.
In my grid, when double clicking on a row, I call the following code:
var win = window.open('#Url.Action("Index", "StandaloneViewer")', '_blank',
'width=600,height=800,scrollbars=yes');
var domainOrigin = document.location.origin;
var message = 'My Message';
win.postMessage(message, domainOrigin);
and in my Index.cshtml, I've got the following:
$(document).ready(function () {
window.addEventListener('message', function (event) {
debugger;
var domainOrigin = document.origin;
var domainPath = document.location.href;
if (event.origin !== domainOrigin) return;
...
}, false);
});
I've also tried the same code in the load event:
$(window).on("load", function () {
window.addEventListener('message', function (event) {
debugger;
var domainOrigin = document.origin;
var domainPath = document.location.href;
if (event.origin !== domainOrigin) return;
...
}, false);
});
but to no avail! Any ideas what I may be missing? I've got the same scenario working just fine when sending a message to an iframe but I have a use case where I need to launch a separate browser and send a message to it.
I'm currently testing this on the latest version of Chrome.
Thanks.

Permission denied when trying to change browser window title

I have a servlet that generates a PDF and the output goes to a new browser window.
I am attempting to replace the title of that new window using the updateTitle() function below.
However, when I try to assign the report name (repName) to the window instance, IE11 throws a "Permission denied" error. Any ideas?
function showReport(url, repName){
var repWin = window.open(url);
updateTitle(repWin, repName)
}
function updateTitle(repWin, repName) {
setTimeout(function() {
repWin.document.title = repName; //IE11 console throws PERMISSION DENIED here
}, 3000);
}
You will need to use something like postMessage.
On your original window:
function showReport(url, repName) {
var repWin = window.open(url);
repWin.postMessage('setTitle:' + repName, '*');
}
On the repWin:
function updateTitle(message) {
var m = message.data.split(':'),
eventType = m[0],
data = m[1];
if (message.origin === 'YOUR_URL_HERE' && eventType === 'setTitle' ) {
repWin.document.title = data;
}
}
window.addEventListener("message", updateTitle, false);
Note: This will obviously only work if you can modify the source for the window you are opening.

Redirect javascript failing in all but Chrome

Trying to have a webpage manage a redirect, if a deeplink fails to open. If the deeplink opens, great. if it doesn't within 2 seconds, I want it to go to my website.
<script type="javascript">
setTimeout(function () { window.location = "http://mywebsite.com"; }, 25);
window.location = "my://app";
</script>
I've tested in Chrome and it works, but Firefox, IE, and Safari all block the script.
Anyone have any idea on how to handle this?
window.location.assign("http:mywebsite.com") may be a better alternative as I believe calling that function fires some additional events that may make the lifecycle of the page easy to manage.
Also in about all except Chrome you can use an IFrame to attempt to launch your protocol handler. This will help prevent the page going to about:blank and/or your script stopping due to navigating away from the page.
var createIframe = function(id, url, timeout, callback) {
var iframe;
iframe = document.createElement("iframe");
iframe.hidden = true;
iframe.id = id;
iframe.src = url;
var data = {}
data.id = id;
data.iframe = iframe;
return setTimeout(callback, timeout, null, data);
}
createIframe('tempFrame', 'http://mywebsite.com', 25, function(err, data) {
if(!err && data){
var iframe = data.iframe;
var id = data.id;
iframe = document.getElementById(id);
iframe.parent.removeChild(iframe);
}
else {
console.log('There was an error createing and removeing the iframe');
}
}

With javascript, how do you get final result URL after 302 redirect on img src?

If there is an img tag in a page whose final image it displays comes after a 302 redirect, is there a way with javascript to obtain what that final URL is after the redirect? Using javascript on img.src just gets the first URL (what's in the page), not what it was redirected to.
Here's a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/
No, this is not possible. src is an attribute and it does not change.
I know this question is old, and was already marked answered, but another question that I was trying to answer was marked as a duplicate of this, and I don't see any indication in any of the existing answers that you can get the true URL via the HTTP header. A simple example (assuming a single image tag on your page) would be something like this...
var req = new XMLHttpRequest();
req.onreadystatechange=function() {
if (req.readyState===4) {// && req.status===200) {
alert("actual url: " + req.responseURL);
}
}
req.open('GET', $('img').prop('src'), true);
req.send();
If you are open to using third party proxy this can be done. Obviously not a javascript solution This one uses the proxy service from cors-anywhere.herokuapp.com. Just adding this solution for people who are open to proxies and reluctant to implement this in backend.
Here is a fork of the original fiddle
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.ajax({
type: 'HEAD', //'GET'
url:document.getElementById("testImage").src,
success: function(data, textStatus, request){
alert(request.getResponseHeader('X-Final-Url'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('X-Final-Url'));
}
});
based on http://jsfiddle.net/jfriend00/Zp4zG, this snippets works in Firefox 17.0:
alert(document.getElementById("testImage").baseURI)
It doesn't work in Chrome. Not tested anything else-
Here is a workaround that I found out. But it works only if the image on the same domain otherwise you will get an empty string:
var img = document.getElementById("img");
getSrc(img.getAttribute("src"), function (realSrc) {
alert("Real src is: " + realSrc);
});
function getSrc(src, cb) {
var iframe = document.createElement("iframe"),
b = document.getElementsByTagName("body")[0];
iframe.src = src;
iframe.className = "hidden";
iframe.onload = function () {
var val;
try {
val = this.contentWindow.location.href;
} catch (e) {
val = "";
}
if (cb) {
cb(val);
}
b.removeChild(this);
};
b.appendChild(iframe);
}
http://jsfiddle.net/infous/53Layyhg/1/

Categories

Resources