支付宝小程序开发中我们使用的 my
其实就是 jsbrige 注入的一个对象。
JSBridge,简单来说就是web和native之间的桥梁,有了它你就可以在web页面中唤起native应用提供的能力。例如:唤起相册,获取应用登陆用户信息等等。
在支付宝小程序中,’my’ 这个对象可读可写。
my.a = 1
console.log(my.a) // 1
遍历 my 对象
Object.keys(my).forEach(key => {
console.log(key);
})
结果:
isIDE
on
off
emit
callSync
call
reLaunch
navigateTo
switchTab
redirectTo
navigateBack
postMessage
createAnimation
pageScrollTo
loadPlugin
SDKVersion
ExtSDKVersion
getExtConfigSync
getAppIdSync
getExtConfig
canIUse
onAppShow
offAppShow
onAppHide
offAppHide
getLaunchOptionsSync
onError
offError
onUnhandledRejection
offUnhandledRejection
env
createWorker
connectSocket
downloadFile
uploadFile
request
uploadFileToAliCloud
createInnerAudioContext
getBackgroundAudioManager
createAudioContext
reportAnalytics
reportCustomEvent
getChinfoChain
appendChinfoChain
createSelectorQuery
navigateToMiniService
navigateBackFromMiniService
startMiniService
setOptionMenu
getOpenUserInfo
getPhoneNumber
getIDNumber
getRecorderManager
getUpdateManager
getFileSystemManager
createIntersectionObserver
_fireIntersectionObserver
loadFontFace
createRDSContext
stopPullDownRefresh
hideKeyboard
__reportFrameworkPerf
reportCustomError
saveSnapshot
saveTemplateSnapshot
showSharePanel
hideDebugVersion
getSelectedTextRange
canvasToTempFilePath
preloadCanvasImage
createCanvasContext
_createCanvas
_createOffscreenCanvas
createWebViewContext
createAICameraContext
createARContext
createCameraContext
createLivePlayerContext
createLivePusherContext
createLottieContext
createMapContext
createVideoContext
rpc
ocr
ap
startRecord
stopRecord
cancelRecord
playVoice
pauseVoice
resumeVoice
stopVoice
playBackgroundAudio
pauseBackgroundAudio
stopBackgroundAudio
seekBackgroundAudio
getBackgroundAudioPlayerState
onBackgroundAudioPlay
offBackgroundAudioPlay
onBackgroundAudioPause
offBackgroundAudioPause
onBackgroundAudioStop
offBackgroundAudioStop
getAvailableAudioSources
openBluetoothAdapter
closeBluetoothAdapter
getBluetoothAdapterState
startBluetoothDevicesDiscovery
stopBluetoothDevicesDiscovery
getBluetoothDevices
getConnectedBluetoothDevices
connectBLEDevice
disconnectBLEDevice
writeBLECharacteristicValue
readBLECharacteristicValue
notifyBLECharacteristicValueChange
getBLEDeviceServices
getBLEDeviceCharacteristics
onBLECharacteristicValueChange
offBLECharacteristicValueChange
onBLEConnectionStateChanged
offBLEConnectionStateChanged
onBluetoothDeviceFound
offBluetoothDeviceFound
startBeaconDiscovery
stopBeaconDiscovery
getBeacons
onBeaconUpdate
offBeaconUpdate
onBeaconServiceChange
offBeaconServiceChange
openBLEPeripheral
closeBLEPeripheral
addPeripheralService
removePeripheralService
updateCharacteristic
startBLEAdvertising
stopBLEAdvertising
onBluetoothAdapterStateChange
offBluetoothAdapterStateChange
onCharacteristicRead
offCharacteristicRead
onCharacteristicWrite
offCharacteristicWrite
onCharacteristicDidSubscribe
offCharacteristicDidSubscribe
onCharacteristicDidUnsubscribe
offCharacteristicDidUnsubscribe
addPhoneContact
getSystemInfoSync
onGyroscopeChange
offGyroscopeChange
onAccelerometerChange
offAccelerometerChange
onCompassChange
offCompassChange
getServerTime
makePhoneCall
vibrate
watchShake
rsa
sendSMS
setKeepScreenOn
setClipboard
getClipboard
scan
getSystemInfo
setScreenBrightness
getScreenBrightness
startWifi
stopWifi
connectWifi
getWifiList
setWifiList
getConnectedWifi
onGetWifiList
offGetWifiList
onWifiConnected
offWifiConnected
onMemoryWarning
offMemoryWarning
vibrateLong
vibrateShort
getHCEState
startHCE
stopHCE
onHCEMessage
offHCEMessage
sendHCEMessage
getBatteryInfo
getBatteryInfoSync
onDeviceMotionChange
offDeviceMotionChange
getDeviceInfo
registerSSID
unregisterSSID
getCarrierName
isSystemRoot
setScreenOrientation
getScreenOrientation
getDeviceID
exit
seNFCServiceIsv
addEventCal
addEventCalendar
onLowPowerWarning
offLowPowerWarning
isLowPowerMode
getLocation
openLocation
chooseLocation
reGeoCode
geoCode
onContinuousLocation
offContinuousLocation
startContinuousLocation
stopContinuousLocation
calculateRoute
compressImage
previewImage
chooseFileFromDisk
chooseImage
chooseVideo
saveImage
getImageInfo
saveVideoToPhotosAlbum
generateImageFromCode
saveImageToPhotosAlbum
textToSpeech
onAudioInterruptionBegin
onAudioInterruptionEnd
offAudioInterruptionBegin
offAudioInterruptionEnd
httpRequest
sendSocketMessage
closeSocket
onSocketOpen
offSocketOpen
onSocketMessage
offSocketMessage
onSocketError
offSocketError
onSocketClose
offSocketClose
getNetworkType
onNetworkStatusChange
offNetworkStatusChange
sendMtop
getTBCode
setTBSessionInfo
getTBSessionInfo
openRpc
tradePay
getUserInfo
getAuthCode
authorize
getAuthUserInfo
ARScan
addCardAuth
openSetting
getSetting
openCustomerService
getConfigService
getOpenUserData
openOtherApplication
donateInBrowser
getStorageInfo
getStorageInfoSync
setStorage
setStorageSync
getStorage
getStorageSync
clearStorage
clearStorageSync
removeStorage
removeStorageSync
showAuthGuide
getAuthStatus
alert
confirm
prompt
showToast
hideToast
showLoading
hideLoading
showNavigationBarLoading
hideNavigationBarLoading
setNavigationBar
showActionSheet
choosePhoneContact
chooseAlipayContact
datePicker
chooseCity
multiLevelSelect
optionsSelect
chooseContact
hideShareMenu
startPullDownRefresh
setTransparentTitle
showBackToHomepage
setViewTop
setCanPullDown
setBackgroundImage
removeBackgroundImage
setBackgroundColor
setBackgroundTextStyle
setBackButton
setLocatedCity
onLocatedComplete
setTabBarBadge
removeTabBarBadge
showTabBarRedDot
hideTabBarRedDot
setTabBarStyle
setTabBarItem
showTabBar
hideTabBar
getTitleColor
regionPicker
getMenuButtonBoundingClientRect
onUserCaptureScreen
offUserCaptureScreen
onTitleCloseClick
offTitleCloseClick
onTitleMoreClick
offTitleMoreClick
iotCreateService
iotCheckService
saveFile
removeSavedFile
getSavedFileInfo
getSavedFileList
getFileInfo
openDocument
openTaobao
reportBizReady
getVisitToken
navigateToCouponDetail
openCardList
openVoucherList
openTicketList
openCardDetail
openVoucherDetail
openTicketDetail
openMerchantCardList
openMerchantVoucherList
openMerchantTicketList
openKBVoucherDetail
paySignCenter
zmCreditBorrow
textRiskIdentification
openCarService
openChatWindow
__openLifePayment
chooseAddress
getAddress
startZMCreditRent
zmRentTransition
chooseInvoiceTitle
zmFreeDeposit
hideAddToDesktopMenu
hideAllAddToDesktopMenu
hideFavoriteMenu
hideAllFavoriteMenu
setCustomPopMenu
getRunScene
navigateToMiniProgram
navigateBackMiniProgram
isCollected
isFavorite
addToFavorite
removeFromFavorite
onFavorite
offFavorite
onInternalFavorite
offInternalFavorite
canFavorite
hideBackHome
getRunData
isSpeechRecognizeAvailable
startSpeechRecognize
stopSpeechRecognize
onSpeechRecognizeResult
offSpeechRecognizeResult
onSpeechRecognizeError
offSpeechRecognizeError
startZMVerify
startAPVerify
createRtcRoomContext
getExtConfig
所有在 my 这个对象上面挂载的方法都在这里了,比文档里面的要多得多。
on
off
emit
// A 页面
my.on('test',(res)=>{console.log(1)}) // 被触发,回调被执行,打印出 {a:1}
// B 页面
my.emit('test',{a:1})
这三个函数明显是事件总线的实现机制,经过测试完全可用(未测试低版本基础库) ~~~~
通过 my 实现全局数据共享
一般小程序里面全局数据我们使用 globalData 处理,它本质上也只是一个全局对象。my 的性质和他类似,我们甚至可以修改 my 本身的数据,实现全局的页面数据共享
// A 页面
my.a=1
// B 页面
console.log(my.a) // 1
完全没问题,这还是引用类型数据,如果修改就直接修改啦,不需要获取上一个页面的实例,然后再去写一大摞代码~
eg:
const pages = getCurrentPages();
const lastPage = pages[pages.length - 2];
lastPage.setData({
a: 1,
});
一对比,明显优雅太多太多了。
警告
本篇博客的一些技法,都不是常规业务实现办法,责任自负。
小程序的这些非公共方法,在使用的时候,最好能做一层 polyfill,防止某些环境某些方法不存在。
参考资料: