Document ready in new window, cross-domain - javascript

how can I check if the document in new window is ready AFTER the document reloads.
Here is my example:
I need to get a search result page to new window from some site (it's cross-domain). I need to first make POST request (they probably store search params in session) and then go to reslut page.
Here is my code:
var windowname = "window"+(new Date().getTime()); // so I can open multiple windows, not very relevant
var new_window = window.open("", windowname); // prepare named window
// prepare form with post data targeted to new window
var dataform = $("<form method='post' target='"+windowname+"' action='https://www.ebi.ac.uk/chembldb/compound/smiles/'><input name='smiles' value='"+$("#id_smiles").text()+"'></form>");
// Need to get the form into page for Mozilla, webkit allows to submit forms that are not in page
$("body").append(dataform);
// submit the form and remove it, no need to keep it
dataform.submit().remove();
// form opens in my new window
$(new_window.document).ready(function(){
// this is carried out apparently too soon, because the POST data didn't work
// when I use timeout (commented below, but i don't like this solution) it works
window.open("https://www.ebi.ac.uk/chembldb/index.php/compound/results/1/chemblid/asc/tab/smiles", windowname);
// setTimeout( function(){window.open("https://www.ebi.ac.uk/chembldb/index.php/compound/results/1/chemblid/asc/tab/smiles", windowname)}, 1000);
});
On that site the first make POST request with AJAX and then they simply, but since it's cross-domain, it is impossible for me.

I believe this is not possible. Even some browser throw exceptions if you use reference of new_window (cross domain).
I got following exception. while trying to access reference of new window with url http://www.google.com (Browser Chrome). and reference has no property with it.
Unsafe JavaScript attempt to access frame with URL http://www.google.co.in/ from frame with URL Document ready in new window, cross-domain. Domains, protocols and ports must match.

You can run the javascript code which is in cross domain, for that you should use either JSONP concept ( http://en.wikipedia.org/wiki/JSONP )/ Cross Origin Resource Sharing( http://en.wikipedia.org/wiki/Cross-origin_resource_sharing ).
Just few changes should be done in apache server settings.

Related

I want to redirect to a website and then click on a button on it

I want to redirect my browser to another website and then click on a action button on that website. I think i should add some time delay in between these two tasks. The code i have written do only one event at a time.
window.location.href = "http://www.google.com";
var delayInMilliseconds = 2000;
setTimeout(function() {
document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
}, delayInMilliseconds);
It's forbidden to do this for security reasons.
In computing, the same-origin policy is an important concept in the
web application security model. Under the policy, a web browser
permits scripts contained in a first web page to access data in a
second web page, but only if both web pages have the same origin. An
origin is defined as a combination of URI scheme, host name, and port
number. This policy prevents a malicious script on one page from
obtaining access to sensitive data on another web page through that
page's Document Object Model.
Source
It is not possible in this manner.
First you change the url of the page which will stop the rest of your JS code from executing. So your timeout will never reach the google page.
Instead implement an <iframe> with the src set to http://www.google.com. Then select the iframe and look for your element in there.
This post will explain how to select the element from an iframe.
Get element from within an iFrame
At the moment you redirect the user with window.location.href any other script won't be executed.
Sort of hack to do what you want is implant script on the second website that will trigger if the user came from a specific URL. Something like that:
var URL = "OLDWEBSITEURL";
var x = window.history.back();
if (x === URL) {
document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
/* or any other code */
}
Note that if the user open the link on different window/tab or/and disable js it won't work.

IE 11 Access deinied when trying to access popup window.document

I'm trying to load a web-application in a new popup window, which sits on a different domain from my application, using a post request (It has to be post request!). Internet explorer is giving me an access denied message when trying to access the document object of the window. I tried other answers posted in similar SO threads, but didn't have any luck...
Note: I can't use '' or 'about:blank' for the url, because IE considers it to be insecure.
Here is what my code currently does
Create window Object
Generate form in JavaScript
Attach form to body of window. // access denied!
Code:
var win = window.open(url, windowname, params);
var form = $(document.createElement('form'))
.attr('action', action)
.attr('method', 'post');
$(win.document.body).html(form.html()); // access denied!
Do you have access to the source code of the content that will be loaded in the popup?
If yes try this:
Why not use static HTML to your pop-up window (i suggest you to use modals) and set the atributes by receiveing them from POST or GET params.
In less words: explore better your back-end and avoid to use DOM manipulation AND POPUPS.
If the answer is no:
Try this: https://stackoverflow.com/a/7397164/5261900

How to run Javascript in newly opened window?

Let's say I have the following code.
window.open(url, windowName, "height=500,width=500")
// This will open a new window with the url.
myFunction();
// Run this function on the newly opened window instead of
// the old one because I need to find a link on the new page.
Right now, myFunction() is getting stuck on the old window.
Update: The new url is the another domain.
Put your myFunction() in the script of the new window.
Then set the onLoad event of that window to run it.
You can get reference to your caller window's document from the new window by:
window.opener.document
There you go with enough links to do pretty much anything.
Update:
Your new window should be from the same domain. Otherwise its against the same origin policy of the browser.
Please see this question:
Ways to circumvent the same-origin policy
You have several options:
edit the source code for the webpage stored at url to include your own custom code that you want to run when the webpage opens. If you only want this code to run when the webpage opens from your popup, you could name the url something like "webpage.html?run_custom_code", then in webpage.html have javascript that only runs if window.location.href.indexOf('run_custom_code') > 0
you can open a webpage that's sole purpose is to run javascript: window.open('javascript:alert()'); although based on your edit this does not seem useful to you.
Use another language like PHP, where you can fetch the contents of another webpage with something like $html = file_get_contents($url);
perform an ajax request to the other url (if it resides on the same domain) and scrape the results to find your link.

How do I detect if window.location failed?

How do I check if a call to window.location failed because the given URL was invalid, etc? Is there some event I can set on the window object or on some other object that can catch this?
Finally got it to work using a "workaround" that is not a generic solution as I originally hoped:
I am using the fact that the link I am trying to open is a custom url scheme (e.g. myxx://localhost) on mobile, and if it fails, the action I want to perform is a redirection to a standard appstore URL (os-specific). The workaround tries to open the custom URL, and if it fails, the timeout function kicks in shortly after, and opens an alternative url:
setTimeout(function() { window.location=alternateUrl; }, 25);
window.location = customUrl;
The downside is that when the customURL fails, a standard safari browser shows a message box that the site could not be opened, but at least it still redirects the user to the appstore.
Not really possible, because when window.location = someURL is executed, before the URL is even tested, your document is removed from the window. You have no code remaining that could test if it worked.
If the link is on the same origin, you may issue an XMLHttpRequest to test if the page is reachable but there doesn't seem to be a way to test if a page isn't requestable just due to cross origin request or because the URL is wrong.
For a general document, I don't know any way to test if a foreign origin page is reachable (but it can be done for an image using the onload event handler).
you can check if page exists using ajax. didn't test code, but it should work.
var rekuest= new XMLHttpRequest();
rekuest.open('GET', 'http://www.thisdoesnotexits.org', true);
rekuest.send();
if (rekuest.status === "404") {alert("not exist!"); }

window.location redirect works, but original URL not showing up in browser history

The code below works well. Here is my problem: The window url redirects, but the original url is not logged in my browser history.
For example, if I visit "http://example.com/page1", the browser redirects to "http://example.com/test", as it should. However, I need the original url visited ("http://example.com/page1") to show up in my browser history so that I can call upon it in a different function.
Is there anyway to get the original url visited to log in my browser's history before redirecting?
<!-- script to enable age verification cookies and ensure people have age checked -->
<script type="text/javascript">
$(document).ready(function(){
if (window.location =="http://example.com/home") {//do nothing
} else {
window.location = "http://example.com/test";
}
});
</script>
I think what you need is window.location.href. This adds the previous URL to the browser history.
I came across this behavior myself and it was because I was loading pages into chrome via the filesystem, i.e. using the file:// protocol. I started an HTTP server, and using that got it to keep the history.
tl;dr, just show me the code
var newUrl = "https://example.com.page2";
// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);
window.open(newUrl, "_top");
JavaScript Browser Navigation With History
There are at least two methods to navigate (redirect) while retaining browser history. With Vanilla JavaScript, one of these are likely what we're looking for:
Easiest: window.location.assign() - part of the Location object in the Browser Window API.
Most Powerfull: window.open() - part of the Browser Window API. window.open() is far more powerful than location.assign() - as it can affect not just the current browser tab, but can also be used within an <iframe>, control which browsing context (a tab, window or iframe) to control, as well as change window features - including options such as the window's default size and position, whether to open a minimal popup window, and so forth.
Keep in mind that window.open() has caveats and usability/user experience issues, as it can open Popups - the exact same popups that most browsers block (Chrome, Firefox) because advertisers / spammers abuse(d) the functionality provided by window.open(). It's still a viable API to use, when used properly.
Browser History can also be managed and controlled directly via the Browser History API, including reading from, modifying existing, and adding new history entries. The History API however does not control navigation, and cannot be used for redirection. It's very often used with Single Page Applications, such as AngularJS, React, Vue.js, Svelte, etc.
Most of the text / descriptions below are directly sourced from MDN Web Docs. Please see the included links for more information. I have slightly modified the descriptions and examples from the MDN API Reference to be more relative to the question asked.
window.location.assign()
Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
The window.location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs, the user can navigate back to the page that called window.location.assign() by pressing the "back" button.
If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.
If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.
window.location.assign() Syntax
window.location.assign(url)
window.location.assign() Parameters
url: Is a string containing the URL of the page to navigate to.
window.location.assign() Example
var newUrl = "https://example.com.page2";
// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);
window.open()
Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/open.
⚠️ NOTE: I've only included a VERY small amount of information related to the extremely versitile window.open() method. I highly recommend you review the full documentation for window.open().
The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, tab, window, or <iframe>) under a specified name.
window.open() Syntax
open()
open(url)
open(url, target)
open(url, target, windowFeatures)
window.open() Parameters
url: Optional
A string indicating the URL or path of the resource to be loaded. If an empty string ("") is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.
target: Optional
A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.
This name can be used as the target attribute of <a> or <form> elements.
windowFeatures: Optional
A string containing a comma-separated list of window features in the form name=value — or for boolean features, just name.
⚠️ NOTE: See the window.open() syntax for the full reference of Window Features.
window.open() Return value
A WindowProxy object. The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.
window.open() Description
The Window interface's open() method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The target parameter determines which window or tab to load the resource into, and the windowFeatures parameter can be used to control the size and position of a new window, and to open the new window as a popup with minimal UI features.
Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.
window.open() Basic Example
For answering the question, the minimal form of window.open() to browse to a new URL, in the same browser tab, retaining browser navigation history.
var newUrl = "https://example.com/page2";
// Navigate to newUrl, adding a new entry to the Browser History
window.open(newUrl, "_top");

Categories