简体   繁体   中英

Change contents of one HTML page from another HTML page

Suppose I have a.html and b.html and I want to change a div element from a.html using a button created in b.html. How can I do that?

a.html

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to RemoteDemo</title>    
</head>
<body>
    <div id="Tvspace">
        <iframe id ="frame" width="560" height="315" src="someRandomURL" frameborder="0"  allowfullscreen></iframe>     
    </div>      
</body>
</html>

b.html

<!DOCTYPE html>
<html>
<head>
    <title>Remote</title>
</head>
<body>
    <button id = "next"> Next </button>
    <!--When I click this button I want the src to change-->
</body>
</html>

I tried this but this only works if the button is on a.html

$("#next").click(function(){
            $("#frame").attr("src", "anotherRandomURL");
        })

*Edit: This answer was assuming that b.html is embedded within a.html as an iframe. Based on comments from the OP it appears that is not the case.

If a.html and b.html are actually opened in different browser windows/tabs, there are a couple of possible work-arounds.

  • The best would be to insert a server in the process. This is probably a good place for WebSockets (especially for a.html). On b.html you would have a websocket or ajax that would trigger from the click event. Then the server would contact a.html over an open WebSocket to notify it of the click, and you could have JavaScript to change the iframe src.
  • Depending on the browser it might also be possible to create a browser plugin. Probably not a good solution though.

Original answer assuming b.html was in an iframe on a.html

This only works if your iframe is not cross-origin (see same origin policy )

in a.html, i'm assuming your src is b.html:

    <iframe id ="frame" width="560" height="315" src="b.html" frameborder="0"  allowfullscreen></iframe>     

in b.html, do something like this script:

<body>
    <button id = "next"> Next </button>
    <script>
        var btn = document.querySelector('#next');
        btn.onclick = function(e){
            var pdoc =  window.parent.document;
            var frame = pdoc.querySelector('#frame');
            frame.src = 'watch.txt';
            var div = pdoc.createElement('div');
            div.innerHTML = 'Hello World';
            pdoc.body.append(div);
        };
     </script>
</body>

Working with jQuery across frames is possible, but you have to keep in mind that the two frames would both need to have the jQuery library included as a script tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM