search

Home  >  Q&A  >  body text

javascript - Click on one page button to display text on another page

I want to click the button on one page and then display the text in the p element of another page. Both pages import js. How can I succeed?

世界只因有你世界只因有你2769 days ago741

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-05-19 10:30:21

    According to your description, communication should be between two web pages in the same domain (same protocol, host name, port). In this case, it can be achieved through localStorage of h5. No need to go through the server.

    1. When the button on page a is clicked, set a pair of new localStorage values.

    $("#in").click(function(){
        localStorage.setItem("setText","hello")
    })

    2. Listen to the storage event of window on page b. When this event is triggered, it means that the stored data has changed. The key attribute of the event event object is used to determine the changed key value. If it is the setText we set, we can set the content for $("#out").

    window.addEventListener("storage",function(e){
        if(e.key=="setText"){
            var text=localStorage.getItem("setText")
            $("#out").text(text);
        }
    });

    Because page b listens to the storage event, after refreshing the page, if the setText value set when page a is clicked is still the original value, this event will not be triggered. If you want this element to still display the value just set after page b is refreshed, you should also add a judgment to page b:

    if(localStorage.getItem("text")){
        h.innerText=localStorage.getItem("text")
    }

    If you have any questions, I hope we can discuss them.

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:30:21

    If it is an iframe, use postMessage

    If there are two separate web pages, a forwarding needs to be done on the server side. Page A sends data and the server stores it in the database. Page B does a polling to check whether the data has changed and updates the data if there is any change

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:30:21

    postMessage

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:30:21

    I didn’t understand your needs, I boldly guessed that what the questioner needs is websock

    reply
    0
  • Cancelreply