Skip to content

Commit

Permalink
refactor: injectJavascript in the source html
Browse files Browse the repository at this point in the history
  • Loading branch information
linonetwo committed Nov 29, 2024
1 parent 8f87120 commit f5f27a2
Show file tree
Hide file tree
Showing 7 changed files with 14 additions and 17 deletions.
11 changes: 6 additions & 5 deletions src/pages/WikiWebView/CustomWebview.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import React, { MutableRefObject, PureComponent } from 'react';
import { Text } from 'react-native-paper';
import { WebView, WebViewMessageEvent } from 'react-native-webview';
import type { WebViewErrorEvent, WebViewNavigationEvent } from 'react-native-webview/lib/RNCWebViewNativeComponent';
import { FAKE_USER_AGENT } from '../../constants/webview';

interface CustomWebViewProps {
backgroundColor: string;
injectedJavaScriptBeforeContentLoaded: string;
onLoadEnd: () => void;
injectedJavaScript: string;
onLoadEnd: (event: WebViewNavigationEvent | WebViewErrorEvent) => void;
onLoadStart: () => void;
onMessageReference: MutableRefObject<(event: WebViewMessageEvent) => void>;
preferredLanguage: string | undefined | null;
Expand All @@ -23,7 +24,7 @@ export class CustomWebView extends PureComponent<CustomWebViewProps> {
onLoadEnd,
onLoadStart,
onMessageReference,
injectedJavaScriptBeforeContentLoaded,
injectedJavaScript,
triggerFullReload,
} = this.props;

Expand All @@ -47,12 +48,13 @@ export class CustomWebView extends PureComponent<CustomWebViewProps> {
mixedContentMode='always'
allowsAirPlayForMediaPlayback
allowsFullscreenVideo
javaScriptEnabled
userAgent={FAKE_USER_AGENT}
// add DOCTYPE at load time to prevent Quirks Mode
source={{
html: `<!doctype html><html lang="${
preferredLanguage ?? 'en'
}"><head><meta charset="UTF-8" /></head><body><div id="tidgi-mobile-webview-before-loaded-place-holder"/></body></html>`,
}"><head><meta charset="UTF-8" /></head><body><div id="tidgi-mobile-webview-before-loaded-place-holder"/>Loading...<script>${injectedJavaScript}</script></body></html>`,
/**
* Add baseUrl to fix `SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.`
* @url https://github.com/react-native-webview/react-native-webview/issues/1635#issuecomment-1021425071
Expand All @@ -75,7 +77,6 @@ export class CustomWebView extends PureComponent<CustomWebViewProps> {
onLoadStart={onLoadStart}
onMessage={onMessageReference.current}
ref={webViewReference}
injectedJavaScriptBeforeContentLoaded={injectedJavaScriptBeforeContentLoaded}
webviewDebuggingEnabled={true /* Open chrome://inspect/#devices , or Development menu on Safari to debug the WebView. https://github.com/react-native-webview/react-native-webview/blob/master/docs/Debugging.md#debugging-webview-contents */}
/>
);
Expand Down
6 changes: 3 additions & 3 deletions src/pages/WikiWebView/WikiViewer.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Dimensions } from 'react-native';
import { Dimensions, Platform } from 'react-native';
import { MD3Colors, ProgressBar, Text, useTheme } from 'react-native-paper';
import { webviewPreloadedJS as ipcCatWebviewPreloadedJS } from 'react-native-postmessage-cat';
import { styled } from 'styled-components/native';
Expand Down Expand Up @@ -140,10 +140,10 @@ export function WikiViewer({ wikiWorkspace, webviewSideReceiver, quickLoad }: Wi
onLoadEnd={onLoadEnd}
onLoadStart={onLoadStart}
onMessageReference={onMessageReference}
injectedJavaScriptBeforeContentLoaded={preloadScript}
injectedJavaScript={preloadScript}
triggerFullReload={triggerFullReload}
/>
</WebViewContainer>
</>
);
};
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable unicorn/no-null */
import { max } from 'drizzle-orm';
import { ExpoSQLiteDatabase } from 'drizzle-orm/expo-sqlite';
import { SQLiteDatabase, SQLiteStatement } from 'expo-sqlite/next';
import { SQLiteDatabase, SQLiteStatement } from 'expo-sqlite';
import { Readable } from 'readable-stream';
import { sqliteServiceService } from '../../../services/SQLiteService';
import { TiddlersSQLModel } from '../../../services/SQLiteService/orm';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ export enum OnStreamChunksToWebViewEventTypes {
break;
}
case OnStreamChunksToWebViewEventTypes.CHECK_RECEIVER_READY: {
// @ts-ignore
window.service?.wikiHookService?.setWebviewReceiverReady?.();
break;
}
Expand Down Expand Up @@ -130,7 +129,6 @@ export enum OnStreamChunksToWebViewEventTypes {
try {
script.parentNode.replaceChild(newScript, script);
} catch (error) {
// FIXME: can't catch error `SyntaxError: Can't create duplicate variable: 'A'` on iOS
console.error(`Faile to refresh script tag with error ${(error as Error).message}: newScript, script`, newScript, script, error);
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/pages/WikiWebView/useWikiWebViewNotification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export function useWikiWebViewNotification({ id }: { id?: string }) {
}

async function registerForPushNotifications() {
let token: string | undefined;
if (Platform.OS === 'android') {
await setNotificationChannelAsync('default', {
name: 'default',
Expand Down Expand Up @@ -104,7 +103,7 @@ async function registerForPushNotifications() {
if (finalStatus !== PermissionStatus.GRANTED) {
alert('Failed to get push token for push notification!');
}
token = (await getDevicePushTokenAsync()).data as string;
const token = (await getDevicePushTokenAsync()).data as string;

setNotificationHandler({
handleNotification: async () => ({
Expand Down
2 changes: 1 addition & 1 deletion src/services/ImportService/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
import { SQLiteDatabase, SQLiteStatement } from 'expo-sqlite/next';
import { SQLiteDatabase, SQLiteStatement } from 'expo-sqlite';
import { Dispatch, SetStateAction } from 'react';
import { Writable } from 'readable-stream';
import Chain, { chain } from 'stream-chain';
Expand Down
5 changes: 2 additions & 3 deletions src/services/WikiStorageService/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import * as fs from 'expo-file-system';
import { Observable } from 'rxjs';
import type { IChangedTiddlers, ITiddlerFieldsParam } from 'tiddlywiki';
import { getWikiTiddlerPathByTitle } from '../../constants/paths';
import i18n from '../../i18n';
import { useConfigStore } from '../../store/config';
import { useServerStore } from '../../store/server';
import { IWikiWorkspace } from '../../store/workspace';
Expand All @@ -18,7 +17,7 @@ import { getFullSaveTiddlers } from './ignoredTiddler';
/**
* Service that can be used to save/load wiki data
*
* - proxy by `src/pages/WikiWebView/WikiStorageService/registerWikiStorageServiceOnWebView.ts` to be `window.service.wikiStorageService`
* - proxy by `react-native-postmessage-cat` to be `window.service.wikiStorageService`
* - then used in `plugins/src/expo-file-system-syncadaptor/file-system-syncadaptor.ts` inside webview
*
* Don't forget to register method in WikiStorageServiceIPCDescriptor. Otherwise you will get `window.service.wikiStorageService.methodName is not a function` error.
Expand Down Expand Up @@ -124,7 +123,7 @@ export class WikiStorageService {
orderBy: desc(TiddlerChangeSQLModel.timestamp),
});

if (recentUpdate !== undefined && recentUpdate.operation === TiddlersLogOperation.UPDATE && recentUpdate.title === title) {
if (recentUpdate !== undefined && recentUpdate.operation as TiddlersLogOperation === TiddlersLogOperation.UPDATE && recentUpdate.title === title) {
// If we are frequently update same title, then update the timestamp of last update, instead of put a new UPDATE log.
await transaction.update(TiddlerChangeSQLModel)
.set({ timestamp: newOperation.timestamp })
Expand Down

0 comments on commit f5f27a2

Please sign in to comment.