Caststupider
Caststupider

Reputation: 53

Jquery click event in new window

Hello i wonder if i can open a link and trigger a click like this:

nothing happens at the moment.

$(document).ready(function(){
    window.open("url");
    $("object").delay(2500).trigger("click");
});

Upvotes: 2

Views: 2542

Answers (3)

gerard
gerard

Reputation: 184

Because I didn't see that it was cross-domain, it's almost impossible to invoke javascript into another window.

If you try an iframe with the following code:

$('iframe').load(function() {
    var iframe = this.contentWindow || this.contentDocument;

    $(iframe).find('h1').text('Changed title');
}).attr('src', 'http://example.com');

An error will appear into the console:

Uncaught SecurityError: Blocked a frame with origin "http://fiddle.jshell.net" from accessing a frame with origin "http://example.com". Protocols, domains, and ports must match.

You can try it yourself in this JSFiddle.

Chrome blocks adding custom javascript, because it would be a hudge security leak. For example: you load Facebook into an iframe and you add a event listener on the 'login'-button that you send the username and password to your servers. The user would think he is safely logged in, but in the background the password was send to the other server.

I think you might do it another way. Like a POST request. But I don't know what the situation is.

Upvotes: 0

gerard
gerard

Reputation: 184

It's because you're in the DOM of the current page and not the poup.

If you do the following:

var popup = window.open('/');

popup.addEventListener('load', function() {
    setTimeout(function() {
        $(popup.document.body).find("object").click();
    }, 2500);
}, false);

It will access the DOM of the popup.

See this fiddle for an example to delete the logo http://jsfiddle.net/anrk8n83/1/ on the Fiddle editor.

NOTE This will not work cross-domain.

Upvotes: 1

BenG
BenG

Reputation: 15154

1 way of doing this is using hash

$(document).ready(function(){
    window.open("url#click");
});

on the other page

$(document).ready(function(){
    if(window.location.hash == '#click'){
        $(".button").trigger("click");
    }
});

Upvotes: 1

Related Questions