SCRIPT70: Permission denied when adding options to

2019-04-28 09:05发布

We are having issues when adding options to a select element from an iframe. The code works well in Chrome, Firefox and Opera, but in IE11 we get a "SCRIPT70: Permision denied" when trying to access the recently created option from the parent window.

What we need is to add options to a select element choosing them from a list. The list is shown in a lightbox (with an iframe) and when an element is chosen, it has to be added to the select element and then the lightbox closed (and the iframe destroyed). What we have is something like this (simplified):

A parent window:

<select id="dropdown">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<!-- in the real code, this iframe is shown when a button is pressed -->
<iframe src="iframe.html"></iframe>
<script>
  $(document).ready(function() {
    $('#dropdown').on('change', function() {
      console.log($(this).children().last().val());
    });
  });
</script>

And the iframe.html:

<a href="#" data-val="4">Add 4</a>
<a href="#" data-val="5">Add 5</a>
<a href="#" data-val="6">Add 6</a>
<script>
  $(document).ready(function() {
    $('a').on('click', function() {
      var p = window.parent;
      if(p) {
        var dropdown = p.document.getElementById('dropdown');
        if(dropdown) {
            var opt = new Option($(this).data('val'), $(this).data('val'));
            dropdown.options[dropdown.options.length] = opt;
            //close self
            $('iframe', p.document).remove();
        }
      }
    });
  });
</script>

If you choose any item of the iframe the option is added to the select element and the iframe is destroyed. And now if you access the recently added option in the onchange event attached to the select element you get a "SCRIPT70: Permision denied". And the weirdest thing is that it doesn't happen the first time the event is triggered. You need to trigger the onchange event at least twice to get the error.

You can see a working fiddle

Solution

If we change the way the option is added to the select element it works like a charm.

//dropdown.options[dropdown.options.length] = opt;
dropdown.appendChild(opt);

Other scenarios that doesn't raise the error

The Question

I wish that someone (maybe some Microsoft employee working on the IE team) could explain the details of this strange behaviour.

1条回答
Viruses.
2楼-- · 2019-04-28 09:47

Try putting this in your html page and see if it makes any difference

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
查看更多
登录 后发表回答