首页 > 解决方案 > 如何设置浏览器标签标题并添加图标

问题描述

我正在使用反应导航,并看到 chrome 浏览器选项卡标题被设置为特定导航屏幕的名称。反正有没有将标题覆盖到其他东西,也许还添加一个图标?

我确实看到我可以更改导航器屏幕名称,但是每个名称都必须是唯一的,并且我希望浏览器标题只是一个静态值,而不是在屏幕之间更改。

谢谢

标签: reactjsbrowsertabsnavigationnative

解决方案


是的,你可以做到这一切:

1 - 添加浏览器标签标题并保留导航标题

在下面的示例中,我使用来自 "@react-navigation/stack" 的 createStackNavigator 函数:

const Stack = createStackNavigator();

function Navigator() {
  return (
     <NavigationContainer>
-      <Stack.Navigator >
+      <Stack.Navigator screenOptions={{ title: "My application name here" }}>
         <Stack.Screen
           name="Home"
+          options={{ headerTitle: "My Home" }}
           component={HomeScreen} />
         <Stack.Screen
           name="Details"
+          options={{ headerTitle: "My Details" }}
           component={DetailsScreen} />
       </Stack.Navigator>
     </NavigationContainer>
  );
}
export default Navigator;

2 - 在浏览器标签标题中添加一个图标

我怀疑有没有办法使用反应原生库来做到这一点。希望 javascript “文档”对象在 React 中可用,因此我们可以通过以下方式将图标添加到浏览器选项卡:

 export default function App() {
+  // On android and iOS, trying this block of code will fail and go to the catch block.
+  try {
+    // Select the <head> tag under <body>
+    const headTag = document.querySelector("head");
+    // Create the <link/> tag.
+    const icon = document.createElement("link");
+    // Create the rel="" attribute
+    const attributeRel = document.createAttribute("rel");
+    // Assign the value "icon" to the rel attribute so that attributeRel becomes rel="icon"
+    attributeRel.value = "icon";
+    // Create the href="" attribute
+    const attributeHref = document.createAttribute("href");
+    // Assign your application icon path to the href attribute so that attributeHref becomes href="path/to/my/icon"
+    attributeHref.value =
+      "path/to/my/icon";
+    // Set the rel attibute to <link> so that the icon JS object becomes <link rel="icon"/>
+    icon.setAttributeNode(attributeRel);
+    // Set the href attibute to <link> so that the icon JS object becomes <link rel="icon" href="path/to/my/icon"/>
+    icon.setAttributeNode(attributeHref);
+    // Insert the <link [...] /> tag into the <head>
+    headTag.appendChild(icon);
+  } catch (e) {
+    //Browser tabs do not exist on android and iOS, so let's just do nothing here.
+  }
    return <Navigator />;
 }

这是结果的一些屏幕截图(“path/to/my/icon”已替换为“https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico”,以便您看到 stackoverflow下面的屏幕截图中的图标):

主屏幕

详细信息屏幕

DOM 中的图标


推荐阅读