在Chrome扩展程序中使用VueRouter和Vue.js - 路径段问题

13

我正在使用Vue.js开发一个Chrome扩展程序。在我想要使用路由的部分之前,一切都正常运作。

当我使用以下路由设置时,在我的本地开发服务器上,即localhost:8080/,这不是一个问题:

main.js

import Vue from "vue";
import VueRouter from "vue-router";
import App from "./App.vue";
import OptionComponent from "./OptionComponent.vue";

const routes = [
  { path: '/', component: App },
  { path: '/option', component: OptionComponent },
];

Vue.use(VueRouter); // This makes all the magic hapen and Vue recognizes the router-view and router-link

const router = new VueRouter({
  routes,
});

new Vue({
  el: '#app',
  router,
});

首页.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>CM Server Descriptor</title>
  </head>
  <body>
    <div id="app">
      <router-view></router-view>
    </div>
    <script src="libs/crypt.js"></script>
    <script src="libs/jquery.js"></script>
    <script src="libs/aja.min.js"></script>
    <script src="libs/JSLINQ.js"></script>
    <script src="js/build.js"></script>
  </body>
</html>

当我部署到我的Chrome扩展程序并在那里开始测试时,什么都没有发生。 我发现Chrome扩展程序有一些特殊的路径行为。

进入图像描述

在这里,您可以看到Chrome具有额外的/index.html路径。

然后我尝试了以下内容:

const routes = [
  {path: '/' + chrome.runtime.id + '/index.html', component: App},
  {path: '/' + chrome.runtime.id + '/option', component: OptionComponent},
];

没有帮助。更改为/index/也没有帮助......最后一次尝试是明确告知协议:

  {path: 'chrome-extension://' + chrome.runtime.id + '/', component: App},

同样没什么运气。 我猜VueRouter只对http://协议的URL起作用。

如果有人有想法如何解决这个问题,我会非常感激!


1
我不熟悉vue.js,但我了解Chrome并且它没有内置的Web服务器,因此您需要在扩展中使用相对于manifest.json文件夹的真实HTML文件路径,例如path:'/index.html' - wOxxOm
很遗憾,那个方法没有起作用。我也尝试了{ path: 'index.html/', component: App },但是同样没有成功。 - xetra11
抱歉,我本来想打“/index.html”,这是个笔误。是的,“index.html”与清单文件在同一根目录下。我已经将“index.html”添加到问题中了。 - xetra11
4个回答

9

我曾经遇到过同样的问题,最终我解决了它。由于已经过去一年,所以我不确定是 Chrome 还是 Vue 修复了这个问题。

无论如何,我会为任何新手记录下解决方法:

Chrome 基于文件夹结构传递 URL,没有隐式的 URL 解析。这意味着 / 不会重定向到 index.html。因此,解决方案是:

  • Either add a path for index.html:

    { path: '/index.html', component: App },
    
  • Or add a path for your app and manual push to it when loaded.

    //router.js
    { path: '/app', component: App },
    

文件 App.vue

created(){
    this.$router.push('app');
}

请记住,在Chrome扩展根目录中,路由路径必须完全匹配相对路径。因此,如果您将index.html放在扩展根目录中,您的Vue baseUrl必须是/


6

Chrome指向了您在manifest中注册的popup.html文件,但是由于您的路由器无法找到该文件,因此出现了问题。

将基本URL设置为popup.html(根据其相对于mainfest.json的位置而定)可以解决此问题。

const router = new VueRouter({
  base: '/popup/popup.html',
  mode: 'history',
  routes,
});

这正是它。在我的项目的Dist文件夹中查找,它没有嵌套在弹出目录中。因此,我将基础更改为/popup.html - Leo Fisher
非常感谢,这正是我需要的答案 :D - Sayf-Eddine

0

为了进一步完善Marian的答案,最新版的VueRouter已将base选项移到createWebHistory函数中。因此它看起来应该像这样 -

const routes = /** your route definitions **/[]
createRouter({ history: createWebHistory('popup.html'), routes })

-2

2
这个答案不相关,而且完全是错误的。-1 https://vuejs.org/v2/guide/installation.html#CSP-environments - Silvio Langereis
Vue 2也符合CSP标准,正如我上面的评论所述。 - Jack Clancy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接