Reputation: 1121
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?
Upvotes: 0
Views: 2361
Reputation: 127
You'd better use:
<a href="http://www.mysite.com/mypdf.pdf">
This should download that pdf file.
Upvotes: 2
Reputation: 24587
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?
Upvotes: 0