Skip to content

Commit

Permalink
feat(inBrowser): support callback
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 10, 2018
1 parent b6def4b commit 6c1edbc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/inBrowser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import isFunction from './isFunction'

let isInBrowser: boolean | undefined

/**
* 是否在浏览器环境中。
* 检查是否在浏览器环境中。
*
* @param [callback] 在浏览器环境中执行的回调
* @returns 是(true)或否(false)
*/
export default typeof window === 'object'
&& typeof document === 'object'
&& document.nodeType === 9
export default function inBrowser(callback?: () => void): boolean {
if (isInBrowser === undefined) {
isInBrowser = typeof window === 'object'
&& typeof document === 'object'
&& document.nodeType === 9
}
if (isFunction(callback) && isInBrowser) {
callback()
}
return isInBrowser
}
11 changes: 11 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,17 @@ describe('Disposer', () => {
})
})

describe('inBrowser', () => {
test('无回调', () => {
expect(vtils.inBrowser()).toBeTruthy()
})
test('有回调', () => {
const callback = sinon.fake()
expect(vtils.inBrowser(callback)).toBeTruthy()
expect(callback.calledOnce).toBeTruthy()
})
})

describe('isFunction', () => {
test('是', () => {
expect(vtils.isFunction(() => ({}))).toBeTruthy()
Expand Down

0 comments on commit 6c1edbc

Please sign in to comment.