Fill input text forms on other website in iframe

2020-03-02 07:18发布

I want to autofill textboxes on another website so I'm writing a short script to do this. I'm loading an iframe with a website in it and if this iframe is loaded, it should fill in the input text forms. So I wrote this in autofill.php:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="fill.js"></script>
<iframe name="autofillframe" src="https://e-services.blum.com/main/" style="width:100%; height:100%;"></iframe>

And this I wrote in fill.js:

$(document).ready(function(e) {
    $('#username').val('username');
    $('#kennwort').val('password');
});

Here is a fiddle

If I do it with a .php file instead of a website, it works fine. Here's a demo without website

Can someone give me a hint?

2条回答
地球回转人心会变
2楼-- · 2020-03-02 07:29

By pressing submit button , input value copies from input textbox to iframe textbox (or opposit of it). you can implement it like:

test1.html

<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#submit').click(function(){
                var iframe = document.getElementById('myiframe');
                var doc = iframe.contentDocument || iframe.contentWindow.document;
                var elem = document.getElementById('username');
                doc.getElementsByName('user')[0].value = elem.value;
            });
        });
    </script>
</head>
<body>
    <input type="text" id="username">
    <input type="submit" id="submit">
    <iframe id="myiframe" frameborder="1" src="test2.html"></iframe>
</body>
</html>

And test2.html :

<!DOCTYPE html>
<html>
<body>
    <input type="text" name="user" id="user">
</body>
</html>
查看更多
贼婆χ
3楼-- · 2020-03-02 07:38

When you load a page from a different domain into an iframe, you can't do anything to the iframe page from JavaScript in your page.

As far as the browser is concerned, the iframe is a separate window and you have no access to it. Imagine that the user had a banking page open in one window and your page open in another window. You know that the browser would not let your JavaScript code interfere with the banking page, right?

The same thing applies when the other page is in an iframe. It's still a completely separate browser window, it's just positioned so it looks like it's inside your page.

In your working example, the code works because the username and password fields are not in an iframe from a different domain. They are part of the same page that the JavaScript code is in.

If the iframe is loaded from the same domain as your main page, then you can do anything you want to it, including filling in form fields. The code would be slightly different because you need to access the iframe document instead of the main page document, but that's easy. But if the iframe is from a different domain, you are out of luck.

查看更多
登录 后发表回答