artem_russkikh
artem_russkikh

Reputation: 437

How to get React Native packager ip from JavaScript?

Is there any way to get dynamicly React Native packager ip with port or full path to bundle - jsCodeLocation through JavaScript code? It can be localhost:8081 or 192.168.0.1.xip.io:8081. It depends on the running device - simulator or real device

Upvotes: 4

Views: 2800

Answers (3)

TorukMacaco
TorukMacaco

Reputation: 76

2024 Updated version on 0.73 - TurboModules - New Architecture enabled

const SourceCode = TurboModuleRegistry.getEnforcing("SourceCode");
const scriptURL = SourceCode.getConstants().scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const hostname = address.split(':')[0];
const port = address.split(':')[1];

Upvotes: 2

Cory Robinson
Cory Robinson

Reputation: 5262

import { NativeModules } from 'react-native';
import url from 'url';

const { hostname } = url.parse(NativeModules.SourceCode.scriptURL);

Upvotes: 7

artem_russkikh
artem_russkikh

Reputation: 437

I found NativeModules in ReactNative source code and discover scriptURL here:

import { NativeModules } from 'react-native';

...

const scriptURL = NativeModules.SourceCode.scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const hostname = address.split(':')[0];
const port = address.split(':')[1];

It works on simulator and device!

Upvotes: 15

Related Questions