[英]Chrome Extension to inject dynamic script into header and after opening body tag
我正在嘗試構建一個 Chrome 擴展程序,我試圖將一些動態 javascript 注入到 a) 頁面的 header b) 頁面的正文中,但是這應該在頁面加載時添加我正在努力解決現有文件。
關於如何簡單地完成這項工作的任何好的指導?
請記住,如果您在頁面加載時添加此 javascript,用戶將在您的腳本更改/更新之前看到原始內容的簡短 flash。
要將 console.log 添加到 jquery 中的頭部和主體:
添加到頭部
$('head').append('<script>console.log("Script added to head")</script>');
添加到正文
$('body').append('<script>console.log("Script added to body")</script>');
確認
如果您將這兩個都添加到您的 chrome 控制台,您應該會看到如下內容:
Script added to head
Script added to body
如果您在 HTML(Jquery 的$('html').html()
)中搜索此腳本,您會得到兩個結果:
> regex = new RegExp(/<script>console\.log\("Script added to \w*?"\)<\/script>/, "g")
> pagetext = $('html').html().match(regex).length
2
當我們添加 2 行控制台日志“腳本已添加到...”時,我們確認已添加這些行。
如果這是在您的內容腳本中,則無需擔心將其嵌套在window.onload 或類似文件中,如果您的清單中有"run_at": "document_end"
manifest.json
在內容腳本 JSON 中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.