passing input from window.open to parent page

前端 未结 1 1671
夕颜
夕颜 2020-12-22 01:29

I have created a frameset, in which one of its frames open a pop-up using window.open . In that window opened i have a form to collect input from users. Input which i\'m try

相关标签:
1条回答
  • 2020-12-22 02:10

    Here is a proposal (I changed small things, please be careful):

    Body of parent.html:

    <button type="button" onclick="popup('popup.html', '', 400, 200);">Opinion</button>
    =&gt;
    <span id="choiceDisplay">No choice.</span>
    

    JavaScript of parent.html:

    function popup(url, title, width, height) {
      var left = (screen.width/2) - (width/2);
      var top = (screen.height/2) - (height/2);
      var options = '';
    
      options += 'toolbar=no,location=no,directories=no,status=no';
      options += ',menubar=no,scrollbars=no,resizable=no,copyhistory=no';
    
      options += ',width='  + width;
      options += ',height=' + height;
      options += ',top='    + top;
      options += ',left='   + left;
    
      return window.open(url, title, options);
    }
    
    function setLang(choice) {
      var languages = {
          'en': 'English',
          'fr': 'French',
          'ch': 'Chinese',
          'por': 'Portugese'
      };
    
      var choiceMessage = 'You have chosen "' + languages[choice] + '".';
    
      document.getElementById('choiceDisplay').innerHTML = choiceMessage;
    }
    

    Body of popup.html:

    <form name="f" onsubmit="sendChoiceAndClose()">
    <fieldset><legend>Chinese/Portuguese</legend>
    
    <p><input type="radio" name="lang" value="ch" checked>Chinese</p>
    <p><input type="radio" name="lang" value="por">Portuguese</p>
    <p><input type="submit" /></p>
    
    </fieldset>
    </form>
    

    JavaScript of popup.html:

    function sendChoiceAndClose() {
      var form = document.forms['f'];
      var choice = form.lang.value;
      opener.setLang(choice);
    
      this.close();
    }
    

    Here is a overview of the result:

    So to give a short explanation, a JavaScript function defined in the opener window is called from the pop-up window to send back the choice information.

    Be careful though, if the JavaScript called contains blocking code (for instance alert(...)), the pop-up will be closed only after the blocking code has finished (i.e. after the alert window has been closed for instance).

    0 讨论(0)
提交回复
热议问题