API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL
ใช้ API การเชื่อมโยงเพื่อรับฟัง URL ขาเข้าขณะที่แอปทำงาน แยกวิเคราะห์พาธและพารามิเตอร์คำค้นของ URL และส่งการกระทำการนำทาง
API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The Linking Module Overview
React Native's built-in Linking module is the interface between your app and the operating system's URL handling system. It serves two purposes: outgoing — opening URLs in browsers, maps, email, phone, and other apps; and incoming — receiving URLs that were used to open your app.
For deep linking to work correctly you need to handle both the cold-start case (app launched by a URL) and the warm-start case (URL arrives while the app is already running). The Linking module provides different APIs for each scenario.
import { Linking } from 'react-native';
// Outgoing:
Linking.openURL('https://example.com');
// Check if URL can be opened:
Linking.canOpenURL('myapp://screen').then(Boolean);
// Incoming - cold launch:
Linking.getInitialURL();
// Incoming - while running:
Linking.addEventListener('url', ({ url }) => {});Comprehensive URL Listener Setup
The recommended pattern handles both cold and warm starts in a single effect. Read getInitialURL() for the cold launch URL and add a listener for warm-start URLs. Both call the same handleURL function to keep routing logic in one place.
Place this effect in your root navigation component or a custom useDeepLink hook so it runs when navigation is available and is properly cleaned up when the component unmounts.
useEffect(() => {
function handleURL(url) {
if (url) routeDeepLink(url);
}
// Cold launch URL:
Linking.getInitialURL().then(handleURL);
// Warm launch URL:
const sub = Linking.addEventListener('url', ({ url }) => handleURL(url));
return () => sub.remove();
}, []);Parsing URL Components
Modern React Native (with Hermes) supports the URL Web API. Construct a URL object from the deep link string to easily access protocol, hostname, pathname, and searchParams. This is far more robust than manual string splitting.
For the scheme myapp://settings/notifications?highlight=push, the hostname is settings, the pathname is /notifications, and searchParams provides the query parameters as a URLSearchParams object.
function parseDeepLink(url) {
// 'myapp://settings/notifications?highlight=push'
const parsed = new URL(url);
return {
screen: parsed.hostname, // 'settings'
path: parsed.pathname.slice(1), // 'notifications'
params: Object.fromEntries(
parsed.searchParams.entries() // { highlight: 'push' }
),
};
}Route Matching and Navigation
With the parsed URL parts, implement a routeDeepLink function that matches the screen name to a navigation action. Use a lookup object or switch statement to map URL screens to navigator screen names and param shapes.
Always guard against invalid or malformed URLs — if the screen is unknown, navigate to the home screen rather than throwing an error. Deep links from external sources should be treated as untrusted input.
function routeDeepLink(url) {
const { screen, path, params } = parseDeepLink(url);
switch (screen) {
case 'profile':
navigation.navigate('Profile', { userId: path, ...params });
break;
case 'product':
navigation.navigate('Product', { productId: path });
break;
case 'settings':
navigation.navigate('Settings', { section: path });
break;
default:
navigation.navigate('Home');
}
}Waiting for Navigation to Be Ready
A common bug: the deep link handler calls navigation.navigate() before the navigation container has mounted and initialized. The navigation ref may be null or the stack may not be set up yet, causing the navigate call to be silently ignored.
Use the onReady callback of NavigationContainer with a ref to detect when navigation is ready. Store pending deep link URLs and process them in onReady and after each navigation state change.
const navigationRef = useNavigationContainerRef();
const pendingUrl = useRef(null);
function handleURL(url) {
if (navigationRef.isReady()) {
routeDeepLink(url);
} else {
pendingUrl.current = url; // queue it
}
}
<NavigationContainer
ref={navigationRef}
onReady={() => {
if (pendingUrl.current) {
routeDeepLink(pendingUrl.current);
pendingUrl.current = null;
}
}}
>Custom URL Scheme vs HTTPS URLs
The Linking API works with both custom scheme URLs (myapp://) and HTTPS universal links (https://yoursite.com/path). For universal links the URL structure is cleaner — the hostname is your domain and the path is the content path — but they require web server configuration to work.
When testing HTTPS deep links locally, use custom scheme URLs in development and universal links in production. The same routeDeepLink function can handle both if you normalize the parsed result to a common structure.
function parseDeepLink(url) {
const parsed = new URL(url);
if (parsed.protocol === 'https:') {
// Universal link: https://myapp.com/profile/123
const parts = parsed.pathname.split('/').filter(Boolean);
return { screen: parts[0], path: parts[1], params: {} };
} else {
// Custom scheme: myapp://profile/123
return {
screen: parsed.hostname,
path: parsed.pathname.slice(1),
params: Object.fromEntries(parsed.searchParams.entries()),
};
}
}Outgoing Links: openURL
Linking.openURL() opens any URL outside your app. Pass HTTPS URLs to open in the browser, tel: URLs to open the dialer, mailto: to open the email client, and third-party app schemes to open specific apps. It returns a Promise — always await and catch errors in case the URL is not supported.
For email links, encode the subject and body in the URL using standard mailto: formatting. On iOS the Phone app handles tel: links; on Android the default dialer handles them.
// Open website:
await Linking.openURL('https://example.com');
// Call a phone number:
await Linking.openURL('tel:+15555551234');
// Compose email:
const subject = encodeURIComponent('Support Request');
const body = encodeURIComponent('Hi, I need help with...');
await Linking.openURL('mailto:support@example.com?subject=' + subject + '&body=' + body);
// Open Twitter profile:
await Linking.openURL('twitter://user?screen_name=reactnative');canOpenURL Safety Checks
Before calling openURL, use Linking.canOpenURL() to verify the device can handle the scheme. On iOS 9+ you must whitelist external schemes in LSApplicationQueriesSchemes in Info.plist, or canOpenURL returns false even if the app is installed.
Expo managed workflow lets you add these whitelist entries via the ios.infoPlist key in app.json. Always provide a fallback (like an HTTPS URL) for when the native app is not installed.
async function openTwitterProfile(username) {
const twitterAppUrl = 'twitter://user?screen_name=' + username;
const twitterWebUrl = 'https://twitter.com/' + username;
const canOpen = await Linking.canOpenURL(twitterAppUrl);
await Linking.openURL(canOpen ? twitterAppUrl : twitterWebUrl);
}
// app.json (iOS whitelist):
// 'ios': {
// 'infoPlist': {
// 'LSApplicationQueriesSchemes': ['twitter', 'instagram']
// }
// }Deep Link URL Sanitization
Deep links from external sources should never be trusted blindly. A malicious link could pass arbitrary values as parameters and attempt navigation to unintended screens or inject data. Always sanitize and validate URL parameters before using them.
For IDs, verify they match expected format (UUID, integer). For screen names, use a whitelist lookup — never navigate to a screen name taken directly from the URL. Log and discard invalid URLs rather than crashing.
const ALLOWED_SCREENS = new Set(['profile', 'product', 'settings', 'home']);
function routeDeepLink(url) {
try {
const { screen, path, params } = parseDeepLink(url);
if (!ALLOWED_SCREENS.has(screen)) {
console.warn('Deep link to unknown screen:', screen);
navigation.navigate('Home');
return;
}
// Validate ID format:
if (path && !/^[a-z0-9-]+$/i.test(path)) {
throw new Error('Invalid path: ' + path);
}
navigation.navigate(capitalize(screen), { id: path, ...params });
} catch (e) {
navigation.navigate('Home');
}
}Tracking Deep Link Sources
Marketing campaigns and notifications often need attribution — knowing which link drove which user behavior. Add UTM parameters or a custom source parameter to deep link URLs, extract them in the handler, and log them to your analytics system.
For example, myapp://product/42?source=email_campaign&campaign=summer_sale tells you the user came from an email campaign. Log this event to Amplitude, Firebase Analytics, or Mixpanel in the routeDeepLink function before navigating.
function routeDeepLink(url) {
const { screen, path, params } = parseDeepLink(url);
// Log attribution:
if (params.source || params.campaign) {
analytics.track('deep_link_opened', {
screen,
source: params.source,
campaign: params.campaign,
});
}
// Then navigate:
navigation.navigate(capitalize(screen), { id: path });
}Testing Deep Links in Production Builds
Deep links behave differently in development (Expo Go) and production builds. Always test deep linking in a production or release build installed on a real device or emulator. Expo Go has its own URL scheme (exp://) which conflicts with custom schemes.
Use TestFlight (iOS) or internal testing track (Android) for end-to-end deep link verification before releasing to the public. Document your URL scheme and all supported paths in a README for QA teams to test every route.
// Supported deep links (document these for QA):
// myapp://home
// myapp://profile/{userId}
// myapp://product/{productId}?highlight={feature}
// myapp://settings/{section}
// myapp://order/{orderId}
// Test with:
// iOS: xcrun simctl openurl booted 'myapp://profile/abc123'
// Android: adb shell am start -a android.intent.action.VIEW -d 'myapp://profile/abc123'Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: the Linking API handles both outgoing URL opens and incoming deep link URLs via getInitialURL and addEventListener, the URL Web API parses deep link components like hostname, pathname, and searchParams cleanly, and deep link routes must be whitelisted and sanitized before navigating to prevent security issues. Next up we configure React Navigation's built-in deep linking support to automatically route URLs to screens.
คำถามที่พบบ่อย
บทเรียน “API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL”
ใช้ API การเชื่อมโยงเพื่อรับฟัง URL ขาเข้าขณะที่แอปทำงาน แยกวิเคราะห์พาธและพารามิเตอร์คำค้นของ URL และส่งการกระทำการนำทาง คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การกำหนดโครงร่าง URL แบบกำหนดเอง
- API สำหรับการเชื่อมโยงและการแยกวิเคราะห์ URL
- การกำหนดค่า Deep Link ของ React Navigation
- Universal Links (Deep Link ผ่าน HTTPS) บน iOS และ Android