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

fix: 增加 window 使用前的判断 #767

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open

fix: 增加 window 使用前的判断 #767

wants to merge 1 commit into from

Conversation

RGCHN
Copy link
Contributor

@RGCHN RGCHN commented Nov 28, 2024

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced safety checks for window object access in multiple functions to prevent runtime errors in non-browser environments.
    • Updated logging functionality to ensure robust error handling when accessing AlipayJSBridge.
  • Documentation

    • Added comments to clarify the necessity of checking the window object during server-side rendering (SSR).

Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

Walkthrough

The changes in this pull request involve modifications to several functions across multiple files to enhance the safety of property access on the window object. The isAndroid, isSimulatorCellPhone, and isWechatMiniApp functions now include checks for the existence of window before accessing its properties. Similarly, the handling of the AlipayJSBridge object in native-log.ts and utils.ts has been updated to use optional chaining, preventing potential runtime errors in non-browser environments.

Changes

File Path Change Summary
packages/effects-core/src/utils/device.ts Updated isAndroid, isSimulatorCellPhone, and isWechatMiniApp functions to check for window existence.
plugin-packages/alipay-downgrade/src/native-log.ts Modified ap constant to use optional chaining for safer access to AlipayJSBridge.
plugin-packages/alipay-downgrade/src/utils.ts Updated getDowngradeResult function to use optional chaining for AlipayJSBridge. Added comment for SSR.

Possibly related PRs

  • fix: 增加降级插件 window 使用前的判断 #728: This PR modifies the registerEvent function to include a check for the existence of the window object, similar to the changes made in the main PR to enhance safety in accessing window properties.
  • Merge origin/dev into origin/main #753: This PR also adds a conditional check for the window object in the registerEvent function, aligning with the main PR's focus on preventing errors related to window access in non-browser environments.

Suggested reviewers

  • Sruimeng
  • wumaolinmaoan
  • yiiqii

Poem

In a world where windows gleam,
We check for them, or so it seems.
With safety nets, we code and play,
Preventing errors day by day.
A rabbit’s hop, a coder’s cheer,
Robustness blooms, let’s give a cheer! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (4)
plugin-packages/alipay-downgrade/src/native-log.ts (1)

Line range hint 31-33: Consider enhancing error logging details

The catch block could provide more context about why the native logging failed.

Consider this enhancement:

  try {
    ap?.call('localLog', content);
  } catch (e) {
-   console.error(e);
+   console.error('[Native Log Failed]', {
+     reason: e,
+     environment: {
+       isAlipayMiniApp: isAlipayMiniApp(),
+       hasWindow: typeof window !== 'undefined',
+       hasAlipayBridge: typeof window?.AlipayJSBridge !== 'undefined',
+     },
+   });
  }
packages/effects-core/src/utils/device.ts (1)

Add safety checks for browser globals across device detection functions

Several functions directly access browser globals without proper existence checks:

  • isIOS(): Directly uses navigator.platform without checking if navigator exists
  • isIOSByUA(): Uses navigator.userAgent without safety check
  • isAndroid(): Has window check but directly accesses navigator.userAgent
  • isSimulatorCellPhone(): Similar to isAndroid()

Suggested safety improvements:

  • Add typeof navigator !== 'undefined' checks before accessing navigator properties
  • Ensure consistent window/document/screen existence checks across all functions
  • Consider consolidating the safety checks into a shared utility function
🔗 Analysis chain

Line range hint 1-42: Verify safety checks in other browser-dependent functions

While we're adding window checks, other functions in this file also access browser globals and might benefit from similar safety improvements.

Let's check for other potential unsafe browser global access:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct access to browser globals without safety checks
ast-grep --pattern 'navigator.$_' packages/effects-core/src/utils/device.ts
ast-grep --pattern 'window.$_' packages/effects-core/src/utils/device.ts
ast-grep --pattern 'document.$_' packages/effects-core/src/utils/device.ts
ast-grep --pattern 'screen.$_' packages/effects-core/src/utils/device.ts

Length of output: 1128

plugin-packages/alipay-downgrade/src/utils.ts (2)

32-32: LGTM! Consider additional browser API safety checks.

The optional chaining for window?.AlipayJSBridge is a good addition for SSR safety. However, the function also uses other browser APIs like performance.now() that might need similar safety checks.

Consider wrapping browser API calls with safety checks:

- const systemStartTime = performance.now();
+ const systemStartTime = typeof performance !== 'undefined' ? performance.now() : Date.now();

Line range hint 89-97: Enhance safety checks for browser APIs.

While the window check is good, the function still directly accesses document without similar safety checks. Consider making the browser API access more robust.

Consider applying these improvements:

function registerEvent (options: DowngradeOptions) {
  const { autoPause } = options;

-  // SSR时window对象不存在 需要判断
-  window && window.addEventListener('unload', () => {
+  // Check for browser environment
+  const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
+  if (!isBrowser) {
+    return;
+  }
+
+  window.addEventListener('unload', () => {
    getActivePlayers().forEach(player => player.dispose());
  });

  if (autoPause) {
    document.addEventListener('pause', pauseAllActivePlayers);
    document.addEventListener('resume', resumePausedPlayers);
  }
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b122efe and 36d2106.

📒 Files selected for processing (3)
  • packages/effects-core/src/utils/device.ts (2 hunks)
  • plugin-packages/alipay-downgrade/src/native-log.ts (1 hunks)
  • plugin-packages/alipay-downgrade/src/utils.ts (1 hunks)
🔇 Additional comments (2)
plugin-packages/alipay-downgrade/src/native-log.ts (1)

16-16: LGTM! The optional chaining addition improves safety.

The change prevents potential runtime errors when window is undefined in non-browser environments.

Let's verify the usage context of AlipayJSBridge across the codebase:

✅ Verification successful

Optional chaining is correctly applied and consistent with other usages

The verification shows that:

  • In alipay-downgrade/utils.ts, the same optional chaining pattern is already used: window?.AlipayJSBridge
  • In orientation-transformer/device-orientation.ts, explicit undefined checks are used: typeof window.AlipayJSBridge !== 'undefined'
  • The type definition in vendors.d.ts correctly declares AlipayJSBridge as a window property

The change is safe and follows the established patterns in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for AlipayJSBridge usage patterns to ensure consistent handling

# Search for other direct AlipayJSBridge accesses that might need similar safety checks
rg -l "AlipayJSBridge" --type ts

# Check for any existing optional chaining patterns with window
rg "window\?\." --type ts

Length of output: 558


Script:

#!/bin/bash
# Let's check the implementation details of AlipayJSBridge usage in other files

# Check utils.ts implementation
echo "=== alipay-downgrade/utils.ts ==="
rg -A 5 "AlipayJSBridge" plugin-packages/alipay-downgrade/src/utils.ts

# Check device-orientation.ts implementation
echo "=== orientation-transformer/device-orientation.ts ==="
rg -A 5 "AlipayJSBridge" plugin-packages/orientation-transformer/src/device-orientation.ts

# Check vendors.d.ts type definitions
echo "=== types/vendors.d.ts ==="
rg -A 5 "AlipayJSBridge" types/vendors.d.ts

Length of output: 1131

plugin-packages/alipay-downgrade/src/utils.ts (1)

32-32: Verify consistent window safety checks across the codebase.

Let's ensure that similar window safety checks are consistently implemented across all related files.

Also applies to: 89-97

✅ Verification successful

Based on the search results, I can now generate the final response:

Window access is consistently protected across the codebase

The review comment's concern about window safety checks has been verified. The codebase shows consistent patterns:

  • In the same package (alipay-downgrade), window access is properly guarded:

    • src/utils.ts: window?.AlipayJSBridge
    • src/native-log.ts: window?.AlipayJSBridge
  • Other window accesses in the codebase are either:

    • In browser-only contexts (demo/test files)
    • Used with feature detection (e.g., typeof window.AlipayJSBridge !== 'undefined')
    • Or properly guarded with optional chaining
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct window access patterns that might need safety checks
echo "Checking for potential unsafe window access patterns..."
rg -g '*.{ts,js}' 'window\.' --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}'

# Search for AlipayJSBridge access patterns
echo "Checking AlipayJSBridge access patterns..."
rg -g '*.{ts,js}' 'AlipayJSBridge' --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}'

# Look for other browser API usage that might need checks
echo "Checking other browser API usage..."
rg -g '*.{ts,js}' 'document\.|performance\.' --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}'

Length of output: 52171

@@ -39,5 +39,5 @@ export function isAlipayMiniApp (): boolean {
}

export function isWechatMiniApp () {
return window.__wxjs_environment === 'miniprogram';
return window?.__wxjs_environment === 'miniprogram';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use consistent window safety check pattern

While optional chaining helps, it doesn't prevent ReferenceError when window is undefined. Let's maintain consistency with other functions.

Apply this diff:

-  return window?.__wxjs_environment === 'miniprogram';
+  return typeof window !== 'undefined' && window.__wxjs_environment === 'miniprogram';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return window?.__wxjs_environment === 'miniprogram';
return typeof window !== 'undefined' && window.__wxjs_environment === 'miniprogram';

@@ -23,11 +23,11 @@ export function isIOSByUA () {
}

export function isAndroid (): boolean {
return /\b[Aa]ndroid\b/.test(navigator.userAgent);
return window && /\b[Aa]ndroid\b/.test(navigator.userAgent);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Enhance window and navigator safety checks

The current window check is insufficient and could still throw a ReferenceError. Additionally, navigator should be checked before access.

Apply this diff to improve safety:

-  return window && /\b[Aa]ndroid\b/.test(navigator.userAgent);
+  return typeof window !== 'undefined' && typeof navigator !== 'undefined' && /\b[Aa]ndroid\b/.test(navigator.userAgent);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return window && /\b[Aa]ndroid\b/.test(navigator.userAgent);
return typeof window !== 'undefined' && typeof navigator !== 'undefined' && /\b[Aa]ndroid\b/.test(navigator.userAgent);

}

export function isSimulatorCellPhone (): boolean {
return isAndroid() || /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent);
return isAndroid() || (window && /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Optimize safety checks and reduce redundancy

The function has similar safety issues as isAndroid() and includes redundant checks through the isAndroid() call.

Apply this diff to improve safety and efficiency:

-  return isAndroid() || (window && /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent));
+  return typeof window !== 'undefined' && typeof navigator !== 'undefined' && 
+    (/\b[Aa]ndroid\b/.test(navigator.userAgent) || /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return isAndroid() || (window && /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent));
return typeof window !== 'undefined' && typeof navigator !== 'undefined' &&
(/\b[Aa]ndroid\b/.test(navigator.userAgent) || /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant