web-view-api.js 2.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
const webviewIds = []

const UNIAPP_SERVICE_NVUE_ID = '__uniapp__service'
const WEB_INVOKE_APPSERVICE = 'WEB_INVOKE_APPSERVICE'

const publish = function (method, params) {
  const paramsObj = {
    options: {
      timestamp: +new Date()
    },
    name: method,
    arg: params
  }
  if (!window.plus) { // h5
    return window.parent.postMessage({
      type: WEB_INVOKE_APPSERVICE,
      data: paramsObj,
      pageId: ''
    }, '*')
  }
  // app-plus
  if (webviewIds.length === 0) {
    const currentWebview = plus.webview.currentWebview()
    if (!currentWebview) {
      throw new Error('plus.webview.currentWebview() is undefined')
    }
    const parentWebview = currentWebview.parent()
    let webviewId = ''
    if (!parentWebview) {
      webviewId = currentWebview.id
      // throw new Error('plus.webview.currentWebview().parent() is undefined')
    } else {
      webviewId = parentWebview.id
    }
    webviewIds.push(webviewId)
  }
  const paramsString = JSON.stringify(paramsObj)
  if (plus.webview.getWebviewById(UNIAPP_SERVICE_NVUE_ID)) {
    plus.webview.postMessageToUniNView({
      type: WEB_INVOKE_APPSERVICE,
      args: {
        data: paramsObj,
        webviewIds
      }
    }, UNIAPP_SERVICE_NVUE_ID)
  } else {
    plus.webview.getLaunchWebview().evalJS(
      `UniPlusBridge.subscribeHandler("${WEB_INVOKE_APPSERVICE}",${paramsString},${JSON.stringify(webviewIds)});`
    )
  }
}

export default {
  navigateTo ({
    url
  } = {}) {
    publish('navigateTo', {
      url: encodeURI(url)
    })
  },
  navigateBack ({
    delta
  } = {}) {
    publish('navigateBack', {
      delta: parseInt(delta) || 1
    })
  },
  switchTab ({
    url
  } = {}) {
    publish('switchTab', {
      url: encodeURI(url)
    })
  },
  reLaunch ({
    url
  } = {}) {
    publish('reLaunch', {
      url: encodeURI(url)
    })
  },
  redirectTo ({
    url
  } = {}) {
    publish('redirectTo', {
      url: encodeURI(url)
    })
  },
  getEnv (callback) {
    /* eslint-disable standard/no-callback-literal */
    if (window.plus) {
      callback({
        plus: true
      })
    } else {
      callback({
        h5: true
      })
    }
  },
  postMessage (params = {}) {
    publish('postMessage', params.data || {})
  }
}