Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polyfill clipboard API [VER-116] #1141

Merged
merged 4 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions __tests__/jestSetupFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import './openHandleFix'
import mockNotifee from '@notifee/react-native/jest-mock'
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
import mockRNCameraRoll from '@react-native-camera-roll/camera-roll/src/__mocks__/nativeInterface'
import mockClipboard from '@react-native-clipboard/clipboard/jest/clipboard-mock.js'
import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js'
import mockBackHandler from 'react-native/Libraries/Utilities/__mocks__/BackHandler.js'
import mockRNDeviceInfo from 'react-native-device-info/jest/react-native-device-info-mock'
Expand Down Expand Up @@ -109,3 +110,5 @@ jest.mock('react-native/Libraries/Components/Switch/Switch', () => {
default: mockComponent('react-native/Libraries/Components/Switch/Switch')
}
})

jest.mock('@react-native-clipboard/clipboard', () => mockClipboard)
6 changes: 6 additions & 0 deletions ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,8 @@ PODS:
- React-Core
- RNCAsyncStorage (1.21.0):
- React-Core
- RNCClipboard (1.13.2):
- React-Core
- RNDateTimePicker (7.6.2):
- React-Core
- RNDeviceInfo (10.3.0):
Expand Down Expand Up @@ -648,6 +650,7 @@ DEPENDENCIES:
- RNBackgroundGeolocation (from `../node_modules/react-native-background-geolocation`)
- RNBootSplash (from `../node_modules/react-native-bootsplash`)
- "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)"
- "RNCClipboard (from `../node_modules/@react-native-clipboard/clipboard`)"
- "RNDateTimePicker (from `../node_modules/@react-native-community/datetimepicker`)"
- RNDeviceInfo (from `../node_modules/react-native-device-info`)
- "RNFBApp (from `../node_modules/@react-native-firebase/app`)"
Expand Down Expand Up @@ -817,6 +820,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native-bootsplash"
RNCAsyncStorage:
:path: "../node_modules/@react-native-async-storage/async-storage"
RNCClipboard:
:path: "../node_modules/@react-native-clipboard/clipboard"
RNDateTimePicker:
:path: "../node_modules/@react-native-community/datetimepicker"
RNDeviceInfo:
Expand Down Expand Up @@ -946,6 +951,7 @@ SPEC CHECKSUMS:
RNBackgroundGeolocation: f2a2052e63d3bf255de1e2f84a24029f89d91601
RNBootSplash: 4844706cbb56a3270556c9b94e59dedadccd47e4
RNCAsyncStorage: 618d03a5f52fbccb3d7010076bc54712844c18ef
RNCClipboard: 60fed4b71560d7bfe40e9d35dea9762b024da86d
RNDateTimePicker: fc2e4f2795877d45e84d85659bebe627eba5c931
RNDeviceInfo: 4701f0bf2a06b34654745053db0ce4cb0c53ada7
RNFBApp: e4439717c23252458da2b41b81b4b475c86f90c4
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@notifee/react-native": "^7.8.0",
"@react-native-async-storage/async-storage": "1.21.0",
"@react-native-camera-roll/camera-roll": "^7.2.0",
"@react-native-clipboard/clipboard": "^1.13.2",
"@react-native-community/blur": "4.3.2",
"@react-native-community/netinfo": "9.5.0",
"@react-native-cookies/cookies": "^6.2.1",
Expand Down Expand Up @@ -87,8 +88,8 @@
"react-native-flipper": "^0.146.1",
"react-native-fs": "^2.20.0",
"react-native-gesture-handler": "1.10.3",
"react-native-iap": "^12.11.0",
"react-native-google-play-integrity": "github:cozy/react-native-google-play-integrity#1.0.1",
"react-native-iap": "^12.11.0",
"react-native-idle-timer": "^2.2.1",
"react-native-immersive-bars": "^1.0.4",
"react-native-inappbrowser-reborn": "^3.5.1",
Expand Down
42 changes: 39 additions & 3 deletions src/components/webviews/CozyWebView.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Minilog from 'cozy-minilog'
import { useNativeIntent } from 'cozy-intent'

import { jsCozyGlobal } from '/components/webviews/jsInteractions/jsCozyInjection'
import { jsUtils } from '/components/webviews/jsInteractions/jsUtils'
import { useLauncherContext } from '/screens/home/hooks/useLauncherContext'
import {
jsEnsureCrypto,
Expand All @@ -15,6 +16,10 @@ import {
jsEnsureNavigatorShare,
tryNavigatorShare
} from '/components/webviews/jsInteractions/jsEnsureNavigatorShare'
import {
jsEnsureNavigatorClipboard,
tryNavigatorClipboard
} from '/components/webviews/jsInteractions/jsEnsureNavigatorClipboard'
import {
jsLogInterception,
tryConsole
Expand Down Expand Up @@ -95,7 +100,7 @@ export const CozyWebView = ({
innerUri && webviewRef && nativeIntent?.unregisterWebview(innerUri)
}, [innerUri, nativeIntent, webviewRef])

const onAnswer = useCallback(
const onCryptoAnswer = useCallback(
(messageId, response) => {
const payload = JSON.stringify({
type: 'Crypto',
Expand All @@ -108,6 +113,32 @@ export const CozyWebView = ({
[webviewRef]
)

const onNavigatorShareAnswer = useCallback(
(messageId, response) => {
const payload = JSON.stringify({
type: 'NavigatorShare',
messageId,
param: response
})

webviewRef.postMessage(payload)
},
[webviewRef]
)

const onNavigatorClipboardAnswer = useCallback(
(messageId, response) => {
const payload = JSON.stringify({
type: 'NavigatorClipboard',
messageId,
param: response
})

webviewRef.postMessage(payload)
},
[webviewRef]
)

useEffect(() => {
const handleLoginSucess = accountId => {
const payload = JSON.stringify({
Expand Down Expand Up @@ -141,6 +172,8 @@ export const CozyWebView = ({
(function() {
${jsCozyGlobal(route.name, isSecureProtocol)}

${jsUtils}

${jsLogInterception}

${injectedJavaScriptBeforeContentLoaded}
Expand All @@ -153,6 +186,8 @@ export const CozyWebView = ({

${jsEnsureNavigatorShare}

${jsEnsureNavigatorClipboard}

return true;
})();
`
Expand Down Expand Up @@ -212,8 +247,9 @@ export const CozyWebView = ({
rest.onLoad?.(event)
}}
onMessage={async m => {
tryCrypto(m, log, logId, onAnswer)
tryNavigatorShare(m, log, logId, onAnswer)
tryCrypto(m, log, logId, onCryptoAnswer)
tryNavigatorShare(m, log, logId, onNavigatorShareAnswer)
tryNavigatorClipboard(m, log, logId, onNavigatorClipboardAnswer)
tryConsole(m, log, logId)
nativeIntent?.tryEmit(m, componentId)
tryHandleLauncherMessage(m)
Expand Down
123 changes: 123 additions & 0 deletions src/components/webviews/jsInteractions/jsEnsureNavigatorClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import Clipboard from '@react-native-clipboard/clipboard'
import { WebViewMessageEvent } from 'react-native-webview/lib/WebViewTypes'

import { OnAnswerCallback, SubscriberPayload } from './types'

type NavigatorClipboardParams =
| {
method: 'readText'
}
| {
method: 'writeText'
text: string | undefined
}

const jsNavigatorClipboardObservable = `
function queryResultToNativeClipboard(param) {
return new Promise(async (resolve, reject) => {
const messageId = 'EnsureNavigatorClipboard_' + uniqueId()

const errorTimeout = setTimeout(() => {
unsubscribeAnswer(messageId)
console.error('timeout while waiting for native clipboard answer')
reject('timeout while waiting for native clipboard answer')
}, 5000)

subscribeAnswer(messageId, result => {
clearTimeout(errorTimeout)

if (result.error) {
reject(result.error)
} else {
resolve(result)
}
})

const serializedParam = await JSON.stringify(param)

const payload = JSON.stringify({
type: 'NavigatorClipboard',
messageId: messageId,
param: serializedParam
})

postMessage(payload)
})
}
`

const jsNavigatorClipboardBridge = `
// On Android, navigator.clipboard is available but does not work.
// So we overwrite with our implementation even if navigator.clipboard is present.
// https://github.com/react-native-webview/react-native-webview/issues/2869

makePropertyWritable(window, "navigator", "clipboard");

window.navigator.clipboard = {
readText: () => {
const payload = {
method: 'readText'
}

return queryResultToNativeClipboard(payload);
},
writeText: (text) => {
const payload = {
method: 'writeText',
text
}

return queryResultToNativeClipboard(payload);
},
read: () => {
throw new Error('navigator.clipboard.read() is not implemented in flagship app. Please use readText() instead.')
},
write: () => {
throw new Error('navigator.clipboard.write() is not implemented in flagship app. Please use writeText() instead.')
}
}
`

export const jsEnsureNavigatorClipboard = `
${jsNavigatorClipboardObservable}

window.cozy.ensureNavigatorClipboard = function() {
${jsNavigatorClipboardBridge}
}

window.cozy.ensureNavigatorClipboard()
`

export const tryNavigatorClipboard = async (
payload: WebViewMessageEvent,
logger: MiniLogger,
logId: string,
onAnswer: OnAnswerCallback
): Promise<void> => {
try {
const { data: rawData } = payload.nativeEvent

const dataPayload = JSON.parse(rawData) as SubscriberPayload

if (dataPayload.type !== 'NavigatorClipboard') return

const { messageId, param } = dataPayload

const params = JSON.parse(param) as NavigatorClipboardParams

logger.info(`[NavigatorClipboard ${logId}]`, { method: params.method })
try {
if (params.method === 'readText') {
const textFromNativeClipboard = await Clipboard.getString()
onAnswer(messageId, JSON.stringify(textFromNativeClipboard))
} else {
Clipboard.setString(params.text ?? '')
onAnswer(messageId, JSON.stringify(''))
}
} catch (e) {
onAnswer(messageId, JSON.stringify(''))
}
} catch (e) {
logger.error('error', e)
}
}
10 changes: 5 additions & 5 deletions src/components/webviews/jsInteractions/jsSubscribers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,16 @@ export const jsSubscribers = `

const dataPayload = JSON.parse(rawData)

if(dataPayload.type !== 'Crypto' && dataPayload.type !== 'NavigatorShare') {
if(dataPayload.type !== 'Crypto' && dataPayload.type !== 'NavigatorShare' && dataPayload.type !== 'NavigatorClipboard') {
return
}

const { messageId, param: serializedParam } = dataPayload

const param = await webviewParse(serializedParam)

const subscriber = answerSubscribers.find(({ id }) => id === messageId)

if (subscriber) {
unsubscribeAnswer(messageId)

Expand All @@ -66,12 +66,12 @@ export const jsSubscribers = `
id: messageId,
callback: callback
})

console.debug(
\`Subscribers registered answer... \${answerSubscribers.length} answer(s) are now subscribed\`
)
}

function unsubscribeAnswer(messageId) {
answerSubscribers = answerSubscribers.filter(({ id }) => id !== messageId)
console.debug(
Expand Down
71 changes: 71 additions & 0 deletions src/components/webviews/jsInteractions/jsUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
export const jsUtils = `
/**
* Creates a read/writable property which returns a function set for write/set (assignment)
* and read/get access on a variable
*
* @param {Any} value initial value of the property
*/
function createProperty(value) {
var _value = value;

/**
* Overwrite getter.
*
* @returns {Any} The Value.
* @private
*/
function _get() {
return _value;
}

/**
* Overwrite setter.
*
* @param {Any} v Sets the value.
* @private
*/
function _set(v) {
_value = v;
}

return {
"get": _get,
"set": _set
};
};

/**
* Creates or replaces a read-write-property in a given scope object, especially for non-writable properties.
* This also works for built-in host objects (non-DOM objects), e.g. navigator.
* Optional an initial value can be passed, otherwise the current value of the object-property will be set.
*
* @param {Object} objBase e.g. window
* @param {String} objScopeName e.g. "navigator"
* @param {String} propName e.g. "userAgent"
* @param {Any} initValue (optional) e.g. window.navigator.userAgent
*/
function makePropertyWritable(objBase, objScopeName, propName, initValue) {
var newProp,
initObj;

if (objBase && objScopeName in objBase && propName in objBase[objScopeName]) {
if(typeof initValue === "undefined") {
initValue = objBase[objScopeName][propName];
}

newProp = createProperty(initValue);

try {
Object.defineProperty(objBase[objScopeName], propName, newProp);
} catch (e) {
initObj = {};
initObj[propName] = newProp;
try {
objBase[objScopeName] = Object.create(objBase[objScopeName], initObj);
} catch(e) {
// Workaround, but necessary to overwrite native host objects
}
}
}
};
`
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3722,6 +3722,11 @@
resolved "https://registry.yarnpkg.com/@react-native-camera-roll/camera-roll/-/camera-roll-7.2.0.tgz#e1de34175619048019f766858d3563608c2b3ef8"
integrity sha512-7y1lW+b9lpXsqUDCi4Ow0XozVe8OLqN/Pfq6lJpAxbgZ0TEVpVKniQj2ZeLMWsA28eae7JMqGqqj4e9uVp8eOw==

"@react-native-clipboard/clipboard@^1.13.2":
version "1.13.2"
resolved "https://registry.yarnpkg.com/@react-native-clipboard/clipboard/-/clipboard-1.13.2.tgz#28adcfc43ed2addddf79a59198ec1b25087c115e"
integrity sha512-uVM55oEGc6a6ZmSATDeTcMm55A/C1km5X47g0xaoF0Zagv7N/8RGvLceA5L/izPwflIy78t7XQeJUcnGSib0nA==

"@react-native-community/[email protected]":
version "4.3.2"
resolved "https://registry.yarnpkg.com/@react-native-community/blur/-/blur-4.3.2.tgz#185a2c7dd03ba168cc95069bc4742e9505fd6c6c"
Expand Down
Loading