簡體   English   中英

在chrome擴展中,如何使用內容腳本注入一個Vue頁面

[英]In chrome extension, how to use content script to inject a Vue page

我正在嘗試實現一個 JSON 查看器 chrome 擴展。 我已經使用 Vue ( http://treedoc.org ) 實現了查看器。 現在的問題是如何使用 Chrome 擴展內容腳本注入 Vue 頁面。

我發現這篇文章對於在擴展中注入普通的 javascript 文件非常有幫助。 但這是一個已知的 javascript 文件名。

我發現這篇文章和這個vue-cli-plugin-browser-extension有助於將 Vue 用於擴展選項頁面和覆蓋頁面等,因為它們的入口點是 HTML 文件。 但是內容腳本入口點是一個javascript,要在內容腳本中注入一個javascript文件,你需要知道確切的文件名。 使用插件和 Webpack,生成的 javascript 文件會附加哈希,例如“ override.0e5e7d0a.js ”,這是未知的。

最近我正在使用 vuejs 開發 chrome 擴展,並且有相同的要求,需要將整個 Vue 應用程序注入特定網頁,即 google.com,但遺憾的是 vue-router 不起作用。

我使用這個樣板來讓它以最少的更改輕松工作。

使用此樣板創建 Vue 項目后,您需要更新 src/popup/popup.js 以在網頁中注入 vue 應用程序。

...
const div = document.createElement("div")
document.body.insertBefore(div, document.body.firstChild);

new Vue({
   el: div,
   render: h => { return h(App); }
});

在 manifest.json 中添加 vue app 作為內容腳本,而不是 browser_action 或 page_action。

"content_scripts": [{
    "matches": ["*://*.google.com/*"],
    "js": [
        "popup/popup.js"
    ],
    "css": ["/popup/popup.css"]
}]

此處 vue 應用程序將僅在 google.com 上注入。 如果要注入所有網頁,則從 content_scripts 中刪除匹配項

聚苯乙烯

管理到 vue 路由器使用模式抽象並在new Vue({ ..., router })之后調用router.replace("/") new Vue({ ..., router })

vue-cli-plugin-browser-extension在內容腳本的文件vue-cli-plugin-browser-extension中不包含哈希值,因此無需擔心。

要添加內容腳本,請配置插件的componentOptions.contentScripts ,如本示例所示(從 Vue CLI 項目的根目錄下的vue add browser-extension生成):

// vue.config.js
module.exports = {
  //...
  pluginOptions: {
    browserExtension: {
      componentOptions: {
        background: {
          entry: 'src/background.js'
        },
        contentScripts: {
          entries: {
            'content-script': [
              'src/content-scripts/content-script.js'
            ]
          }
        }
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM