What have we come across?


Sometimes we need to jump to a new window, such as to payment, such as to the details page. You say it’s easy. We have window.open() and target=”_blank”, but sometimes these methods are blocked by the browser and can’t jump directly to a new page, so the user has to manually allow it. It’s a bit vague to say that opening a new window to an action must be triggered by the user. The following three methods are all actively triggered by the user

<input type="button" id="btn" onclick="openwin()" />
<script>
  // function1
  document.getElementById('btn').onclick = function() {
    window.open('http://www.alenqi.site')}// function2
  document.getElementById('btn').onclick = function() {
	setTimeout(function () {
	  window.open('http://segmentfault.com');
	}, 1000)}// function3
  window.open('http://www.alenqi.site')
</script>
Copy the code

Function1 pops up new pages as expected, function2 does not; both methods are user-triggered. In fact, if the browser determines that the jump is asynchronous, that is, not immediately responding to the user’s action, it will determine that the script is running and block the jump. Function3 behaves differently for unavailable browsers.

What do we need to do?

  • In a synchronous environment:

    1. Using simulation generationaTag, and then triggers the click event for the tag.
    function openNewWindow(url, id) {
      var a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('target'.'_blank')
      a.setAttribute('id', id)
      if(! document.getElementById(id)) document.body.appendChild(a) a.click() }Copy the code
    1. Use the Form’s Submit method to open a page
    const alipayForm = document.createElement('form')
    alipayForm.id = alipayForm.name = 'alipayForm'
    alipayForm.method = "GET"
    alipayForm.action = 'https://mapi.alipay.com/gateway.do'
    Object.keys(params).forEach(key= > {
      const hidden = document.createElement('input')
      hidden.type = 'hidden'
      hidden.name = key
      hidden.value = params[key]
      alipayForm.appendChild(hidden)
    })
    const alipaySubmit = document.createElement('input')
    alipaySubmit.type = alipaySubmit.value = 'submit'
    alipaySubmit.style = 'display: none'
    alipayForm.appendChild(alipaySubmit)
    document.body.appendChild(alipayForm)
    document.querySelector('#alipayForm').submit()
    Copy the code
  • In an asynchronous environment:

    1. The user clicks to open the page and then redirects the page
    document.getElementById('btn').addEventListener('click'.function() {
      var newWindow = window.open('loading page')
      setTimeout(function() {
        newWindow.location.href = 'http://www.alenqi.site'
      }, 1000)})Copy the code

The above can basically solve the browser blocking page problem.