使用@ angular / cli构建chrome扩展弹出窗口,选项和背景

时间:2017-05-26 18:32:00

标签: angular google-chrome-extension angular-cli

我想创建一个带有弹出窗口,选项页面和后台进程的chrome扩展。所以基本上是一个带有popup.html,options.html和background.html页面的角度应用程序。这是否可以使用角度cli?

今天我可以为每个页面使用多个webpack配置来实现这一点,并且它可以工作。现在我想用angular-cli替换它。任何人都可以指出我正确的方向,即种子项目或首发例子

由于

2 个答案:

答案 0 :(得分:1)

经过大量的谷歌搜索,这个blog post帮助了我。 TLDR;不需要多个应用程序,单个应用程序将使用查询参数。例如在我的manifest.json中,我现在有了这个

"browser_action": {
    "default_popup": "index.html?page=popup"
},
"options_page": "index.html?page=options",
"background": {
    "page": "index.html?page=background",
    "persistent": false
},

然后在路由中定义不同的组件(PopupComponent,OptionsComponent和BackgroundComponent)后,根据'页面进行导航。 PARAM。

答案 1 :(得分:0)

经过大量的努力,并仔细研究了surya的提示和技巧,我设法使解决方案可以使用Angular(9)。


manifest.json

{
...
    "browser_action": {
        "default_popup": "/index.html#/popup"
    },
    "options_page": "/index.html#/options",
    "background": {
        "page": "/index.html#/background",
        "persistent": false
    },
...
}

它使用hash location strategy通过#加载组件。


AppRouting

路由将使用指定的路径,并加载适当的组件(分别为popupoptionsbackground script

const routes: Routes = [
    { path: 'popup', component: PopupComponent },
    { path: 'options', component: OptionsComponent },
    { path: 'background', component: BackgroundComponent },
    { path: '**', component: PopupComponent },
];

@NgModule({
    imports: [RouterModule.forRoot(routes, { useHash: true })],
    exports: [RouterModule]
})
export class AppRoutingModule { }

AppRoutingModule中引用app.module.ts的地方:

注意:我已经为我的OptionsPopup组件创建了功能模块,但是与该答案无关。您可以在这里声明提到的组件,也可以像我对BackgroundComponent所做的那样进行声明。

@NgModule({
    declarations: [
        AppComponent,
        BackgroundComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        OptionsModule,
        PopupModule
    ],
    providers: [
         // This is needed because the manifest loads the index.html file, followed by a #, 
        { provide: LocationStrategy, useClass: HashLocationStrategy }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

设置路由后,我们可以在app.component(自举组件)中使用它通过路由加载正确的组件:

index.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Your Extension title</title>
    <base href="/index.html#/"> <!-- !!Important!! !-->

    <meta name="viewport"
        content="width=device-width, initial-scale=1">
</head>

<body>
    <app-root></app-root> <!-- Root of your application !-->
</body>

</html>

AppComponent

为简单起见,应用程序组件仅包含<router-outlet>,并将协调要加载的组件。

<router-outlet></router-outlet>

注意:必须将base href文件中的index.html设置为以下内容:/index.html#/,否则不会在选项/弹出页面上连续重载识别正确的路线并抛出File not found响应页面。


示例

如果导航到URL,则可以看到路由在不同组件上起作用:

选件

chrome-extension://<Extension ID>/index.html#/options

弹出

chrome-extension://<Extension ID>/index.html#/popup

背景

即使此组件仅用作后台脚本,您仍可以将其用作普通的Angular组件-并仍然利用Angular的功能-如服务,注入等。

chrome-extension://<Extension ID>/index.html#/background