How to Inject Content with a Chrome Extension - MV2 & MV3

  Рет қаралды 41,028

Rusty Zone

Rusty Zone

Күн бұрын

rustyextensions.com/academy Get access to my Browser Extension Academy today!
Hey! In this video we look the different ways you can inject code to a page with a Chrome Extension. There are examples for both manifest version 2 & the new version 3. There are two main methods to do this, using a content script within your manifest file or to inject directly from the background page / service worker when you are on a specific page.
Also mentioned in this video is my new Chrome Extension Academy. This is a brand new course aimed to help guide you along the process of creating an extension, targeted towards anyone looking to create an extension to launch on the Chrome Web Store. If you have any questions or want to suggest an area for the course to cover, feel free to send me an email ( rz.rustyzone@gmail.com ) but I will share more details on this as soon as it's ready! 😀
RELATED LINKS:
Onboarding / Permissions Video: • Chrome Extension Onboa...
Shadow Root Video: • How to use the Shadow ...
Source Code: github.com/rustyzone/Inject-C...
TIMESTAMPS:
0:00 Intro
0:55 New Course
1:07 MV2 Content Script
3:49 MV3 Content Script
4:40 MV2 Background Page
6:53 MV3 Background Page
8:49 Shadow Root
14:45 Chrome Extension Academy
MY ONLINE COURSE:
⛏ My Chrome Extension Course: skl.sh/2Xcr9Va
** Join my community on Skillshare by starting any of my classes or following my profile for the latest classes & updates, this is also the best place to get more in-depth content & development support **
** Get a free trial of Skillshare Premium Membership - www.skillshare.com/r/user/rus... **
FIND ME ONLINE:
📨 Sign up to my email newsletter - rustyzone.substack.com
🌍 My website / blog - russellr.co.uk
🐦 Twitter - / russellbarnard
📺 Subscribe - / @rustyzone
MY MINIMAL SETUP:
💡 Lights amzn.to/2X2rkl6
📷 Tripod amzn.to/350b3S1
🕹 USB-C Adaptor amzn.to/3rEDVsZ
👁 iPhone Lens amzn.to/3qHzgFI

Пікірлер: 89
@mehdikhoudali
@mehdikhoudali 8 ай бұрын
One of the rare people doing videos on chrome extentions, thanks a lot man !
@bashvlas
@bashvlas 3 жыл бұрын
Hello Rusty :) Thank you for the video! Great stuff about using shadow root and making sure that the content script injected from the backend script is not executed twice - shows that you really know your stuff and go into details that other tutorials don't mention. Hope your academy gets a lot of students :)
@LeetCodeSimplified
@LeetCodeSimplified 3 жыл бұрын
Now finally everything makes sense! I was always wondering why some extensions were using a shadow root xD
@XANDE1239
@XANDE1239 2 жыл бұрын
Sensational with your help to unlock a restricted access on a website thank you very much!
@superstarindia10
@superstarindia10 Жыл бұрын
Thank you. This was helpful
@kfliden
@kfliden Жыл бұрын
Great video, I'm interested in the Chrome Extension academy!
@mikeliturria1243
@mikeliturria1243 2 жыл бұрын
Very useful, thanks
@youssefbenamor9547
@youssefbenamor9547 Жыл бұрын
Hello Rusty, thank you for the great explanation! I was wondering if using MV3 we are still able to inject local scripts into testing server and still can debug the source code (not minified) using the extension or not.
@trevno
@trevno 5 ай бұрын
Thank you!
@cyan_sol
@cyan_sol 3 жыл бұрын
Man, this channel have such a nice content. Can you make a video of an extension using a google api like Calendar? it would be awesome
@RustyZone
@RustyZone 3 жыл бұрын
Sure thing! I’ll add this to my list 👍
@dragon3602010
@dragon3602010 3 жыл бұрын
Bonjour, That's freakin cool . I have a question, did u ever use tailwindcss to style a web extension, it would be cool . Thanks 😉
@RustyZone
@RustyZone 3 жыл бұрын
I'll be sure to plan out a video with tailwind, sounds like a great idea!
@FunnyClipsYT
@FunnyClipsYT 2 жыл бұрын
Thanks for the video, I wonder how can we use Bootstrap in our content script without affecting the host page? I mean with shadow root we do other way around. For example let's say the webpage uses bootstrap 4 and I want to use Bootstrap 5 but loading it in the manifest breaks the page. Can you please provide some tips?
@ahmadsameer7415
@ahmadsameer7415 2 жыл бұрын
Thx for the useful video but how can I inject CSS file in the background by MV3
@alxizr
@alxizr Жыл бұрын
Hi. Great content first of all. Elegant and precise. Thank you. I was wondering if you have a guide on creating a chrome extension using React + Vite as an injected page and not via the tool bar. Thank you.
@RustyZone
@RustyZone Жыл бұрын
Great question, I have a few videos on building extensions with react & Vite on the way! 😁 - the closest to this right now i suppose would be the bookmarks video but it's not really anywhere near what you are looking for kzbin.info/www/bejne/m3_CpYCcfLJ3a6c
@alxizr
@alxizr Жыл бұрын
Thanks. I'll watch it. I have couple of nuances I want to verify. It is exhausting reading through docs over and over and miss what I need. As far as I read it is only in matter of the configurations. The actual project is already done. And the last step is to wrap the injection thing ...
@alxizr
@alxizr Жыл бұрын
Just wanted to update you that I figured everything out. It's was a bit confusing, to be honest
@shafu_xyz
@shafu_xyz 2 жыл бұрын
I had this doubt, does all chrome versions support v3, like if I released v3 extension, will that only be installed in newer browsers?
@gabrudude3
@gabrudude3 6 ай бұрын
Hi Rusty, Great video! Thanks for sharing good content. Quick question, is it possible through Chrome extension to login to a page with provided credentials, read page content, fill out a form, and submit, without any manual user interaction? Thanks again!
@RustyZone
@RustyZone 5 ай бұрын
Hey 👋 to some extent yes this is possible, would depend on the specific site but so long as the form element are able to be predictably identified it should be possible
@joshuajaydan
@joshuajaydan Жыл бұрын
Is the shadow root with the tags the only way to CSS style the injected HTML?
@DineshSainath
@DineshSainath Жыл бұрын
Thank you Rusty for a great tutorial. I was wondering how to inject content to the side of the webpage when I click on my extension rather than from the bottom. Is there any way to go about this?
@RustyZone
@RustyZone Жыл бұрын
Is this to change where your injected content appears on the page? As you can decide the exact placement with CSS Or would this more be for a different sidebar element within the browser itself?
@joaocorreia6593
@joaocorreia6593 2 жыл бұрын
Thank you very much for the tips given, a doubt, how can I use a lib and a module type file? Exp. In version 2 I have a background.html with
@senkwito
@senkwito 3 жыл бұрын
I've used this one video to pretty much learn how to write chrome extensions. Thanks a million. One question though, how can we use this shadow root technique to reference css third party libraries in our content scripts (for example, I'd like to use Bulma for styling)
@RustyZone
@RustyZone 3 жыл бұрын
Awesome that is great news!! In terms of styling, you could append a block inside the shadow root and it should work to use getUrl ( developer.chrome.com/docs/extensions/reference/runtime/#examples ) to append en external css file here as well such as Bulma, just be sure to download this and add the file into your extension bundle rather than calling an externally hosted css file
@matanbloom538
@matanbloom538 2 жыл бұрын
Hey buddy Today in the mv2 policy I’m opening my app with an i frame but the changing with mv3 I understand that it won’t be possible, am I right? Thank you
@rishabhrawat2161
@rishabhrawat2161 Жыл бұрын
Hi Sir, I want to load the JS dynamically in the popup.html(extension actual page at top position) page. But in V3 I am not able to do this. Could you please tell me like how can I do that?
@srinidhipatil1935
@srinidhipatil1935 Жыл бұрын
How to add a dynamic script ? Is it prohibited? Is there any other options ?
@gilsonmiranda8372
@gilsonmiranda8372 3 жыл бұрын
Thanks for great video! Could you make a video about making an api call (fetch) to end point using workers and showing the results (response) in the conten_script page? Thanks in advance.
@RustyZone
@RustyZone 3 жыл бұрын
This video here shows a little about using fetch to call an API kzbin.info/www/bejne/bYXYY51opchrbas The main change between using workers and a background page is in the manifest as other than that the flow is very similar. In order to get a response to your content script it comes down to using sendMessage & onMessage as in the video. If you have any questions please let me know :) also i'll also be sure to plan out another video focusing more on api calls.
@gilsonmiranda8372
@gilsonmiranda8372 3 жыл бұрын
@@RustyZone Thank you!!! One last question, what If you make a http request in the site now loaded in browser that needs to use authentication data registered in browser's session (token), the extension Will use It by default while making the request or i should clone sesssion's data and pass as parameters to service worker? Thanks again.
@RustyZone
@RustyZone 3 жыл бұрын
If you are making the request from the background page / service worker I would expect that you would need to pass through any auth data along with the request. I would also imagine this to be slightly different depending on the type of authentication used on each site as well. Happy to look into this more, if there are any specifics you can share.
@gilsonmiranda8372
@gilsonmiranda8372 3 жыл бұрын
@@RustyZone Let's supose I'm already logged in a website and my chrome extension need to make requests in this same website for exemple compiling information to user, in this case the auth data is already stored in browser's session. Will I need to pass session as a parameter to make the request or the extension will use the current session of the tab I'm in as a default session? Sorry, english isn't my first language.
@RustyZone
@RustyZone 3 жыл бұрын
It may be possible but I would always assume the extension is in a different environment from the main area of the page. There is a lot of security around even page variables etc.. so you would have to collect this data first and then perform your requests *unless* the extension is just clicking elements on the page e.g that opens a new tab or performs actions on the page that would use any existing auth, liking a tweet for example. - Happy to chat more via email to go into more specific details ( rz.rustyzone@gmail.com )
@0shaad
@0shaad Жыл бұрын
what Content i can put in pae, can i put links in page through extension
@programador-visual
@programador-visual 2 жыл бұрын
Hi, is there a preview of your course I could check out? thanks
@RustyZone
@RustyZone 2 жыл бұрын
Almost 😅 will share a preview as soon as I can!
@sebastiandelgado6824
@sebastiandelgado6824 10 ай бұрын
Thanks for your video it is awesome, I would like to know if it is possible to make an extension to be able to be working at the background counting the amount of times that you click over a button, but keeping in mind that you as a developer only have access to the HTML file.
@RustyZone
@RustyZone 10 ай бұрын
Hey, can you share a little more info on what you are looking to do here, I sounds like depending on the site you could just inject a content script based on the url on the page and then in there track clicks on / over the button. the reason I say depending on the site is it will need to detect the button on the page a number of ways of doing this but knowing a little more about the site(s) will help suggest the best method! :)
@sebastiandelgado6824
@sebastiandelgado6824 9 ай бұрын
Thanks for replying, well if you really wanna know ... I'm trying to develop an extension for my job, I work for a call center and we a have soft-phone (is an app that works on the browser and we answer the calls on it) ... long story short, we get a bonuses dependening on some metrics and one of them is the release rate, so i was trying to create an extension that counts every time that you click on the release button, and gives you a real time view on how is you RR (Release rate) going daily and also gives you a monthly perspective about how many days you need to achive this etc etc, the main issue is that, I only have access to the HTML file from the browser, I asked chat GPT how to do that and it is telling me to add like 2 lines of code with the id that the extention generates after you install the extention on the browser, but I don't think that they would let me to do that,because the Id has to be add on the back end, like the server ... you know PHP, NODEJS ... in something call CORS; if you can explain me how to do the injection, I can try that, or if you know any other way, I will really appreciate you.
@mostafafotouhi5193
@mostafafotouhi5193 2 жыл бұрын
Hello Rusty I wanna create an overlay page for extension. I mean I have a button on the popup.html and I want to show the overlay page when the user clicks it. I have some things like buttons on the overlay page. how I implement it?
@RustyZone
@RustyZone 2 жыл бұрын
Hey Mostafa, this sounds like you would need to add a content script (to allow you to add code into the page you want to overlay) this would be used by a message event when the user clicks the button in your popup.html that is sent to the content script or to the background page / service worker to inject and execute the script.
@andreyosadchuk
@andreyosadchuk 3 жыл бұрын
Hey Rusty, Could you please explain how to inject a script with MV3 to be able to read page context variables?
@RustyZone
@RustyZone 3 жыл бұрын
Hey Andrey, Yes the mv3 examples for both using a content script or service worker should allow you to read variables from the page, is this for a specific domain?
@andreyosadchuk
@andreyosadchuk 3 жыл бұрын
​@@RustyZone , could you please share some guidance regarding how to set up the extension (manifest + the code) to read the variables? It's not about reading document.title, but the variables set on the page. For example, how to read _octo.app on github.com/rustyzone/ ? The mv2 allows to add scripts and execute eval, but it's not clear what to do with mv3...
@RustyZone
@RustyZone 3 жыл бұрын
Hey Andrey, aha sorry yes I see what you mean now, I had been testing this a few weeks back, don't think I had a working version just yet. I'll check and get back to you on this 🙂
@RustyZone
@RustyZone 3 жыл бұрын
Hey Andrey, been thinking about this and found a sort of workaround that works but not sure if it would pass the web store review process but it *should*. This example basically has a content script which then inject another js file into the dom of the page. This second file can now access the page vars and send a message to the content script which in turn can run as normal. I tested on github and my profile as you can see from the code linked below, important to note the manifest it seems the "web_accessible_resources" part had changed since I last used this for mv3 but this should work but you'd need to change the domain here to get this to work on other sites. The content script itself then listens for events using window sendMessage / listener. github.com/rustyzone/mv3-work-with-page-vars-dom-sendmsg
@andreyosadchuk
@andreyosadchuk 3 жыл бұрын
@@RustyZone , fantastic!! Thank you so much for the guidance and the code example!
@solidiron1544
@solidiron1544 Жыл бұрын
How to use contentDocument and contentWindow or alternative command using Chrome extension.
@SandeepMondal93
@SandeepMondal93 Жыл бұрын
Nice video 😀 Can you please help me with how to execute the content script only when I will click on the extension icon?
@RustyZone
@RustyZone Жыл бұрын
You could do this a couple of ways depending on the permissions you have, but it sounds like you would have an activeTab permission, then have a listener for when this is clicked in your background.service worker e.g developer.chrome.com/docs/extensions/reference/action/#event-onClicked That would then inject the script to the active tab, if you already have a popup with content to show in that area, then you could just also trigger this from within your existing popup logic
@SandeepMondal93
@SandeepMondal93 Жыл бұрын
@@RustyZone Thanks a lot :)
@sounakroy9284
@sounakroy9284 Жыл бұрын
Can you help me to launch new window as i clicked on the extension icon. (my MV3)
@RustyZone
@RustyZone Жыл бұрын
Do you want the popup to remain open after the window / tab is opened?
@Cykotiq
@Cykotiq 3 жыл бұрын
Could you do a video on using the notifications API in MV3? I have tried to make it work, but I get nothing but errors. is there a special onboarding flow required for that too? I heard online that they may have removed it in favor of the native web notifications API, but that cannot be run from background.js as far as I can tell. If I can't figure it out I'll have to resort to adding an onboarding flow and injecting code into the page with chrome.scripting.executeScript to create a fake notification box
@RustyZone
@RustyZone 3 жыл бұрын
Hey, for sure yes happy to look into this and plan out a video. Would you be wanting to send notifications just from your background page / service worker or also from a backend / server etc...?
@Cykotiq
@Cykotiq 3 жыл бұрын
@@RustyZone the app I'm planning would connect to a websocket API (or query a REST API every 5mins) and post a notification when someone you follow goes live. So the notifications would not be sent directly from a backend server, but the background service worker would connect to a server to know when to display a notification and what to display. Thanks to your videos I've already got the oauth, fetch, alarms, and popup messaging parts figured out
@RustyZone
@RustyZone 3 жыл бұрын
I’ve been testing this out with the info in the docs and found a live bug for this, so you must have been doing everything correctly just that service workers had an issue here. It looks like it has been fixed in version 91 of Chrome which you can try today with Chrome Canary (linked all info below) Issue Reported groups.google.com/a/chromium.org/g/chromium-extensions/c/ZNE9hTXAOSU/m/08v5oN7jCgAJ Bug Report bugs.chromium.org/p/chromium/issues/detail?id=1168477 Chrome 91 chromiumdash.appspot.com/commit/4c5b746de1466d5ada93babb84bc8181feaac5f4 Canary www.google.com/intl/en_uk/chrome/canary/
@Cykotiq
@Cykotiq 3 жыл бұрын
@@RustyZone yup, that bug matches the error i was fighting with. Thanks!
@sakthi6023
@sakthi6023 8 ай бұрын
hi can i inject html file like js & css injection from background script?
@RustyZone
@RustyZone 8 ай бұрын
In a way yes, you can inject a js script or function and also css files for the html file you could inject this s an as part of your js. just be sure to include this in your web accessible resources - More info here developer.chrome.com/docs/extensions/reference/scripting/#method developer.chrome.com/docs/extensions/mv3/manifest/web_accessible_resources/
@relax_music668
@relax_music668 2 ай бұрын
how root style width setup?
@imransuleiman2032
@imransuleiman2032 2 жыл бұрын
Hello Rusty, I'm building a chrome extension for the company I work for, I have this issue where I get an error saying "Extension context invalidated" whenever the extension is updated but it goes away when I reload the page. Please a way I can avoid this error at all.
@RustyZone
@RustyZone 2 жыл бұрын
Hey, yes this is due to the contact script trying to connect to the now outdated instance of the background page / service worker - Couple of ways around this, you can ether reinject the content script into the page when the new updated background page / service worker is awake ( good example of this here stackoverflow.com/a/11598753 ) or you could also capture the error and parse to see if it matches this string and reload the page (depends on the type of page you are working with, e.g you may not want to do this is users you have unsaved data)
@khokon_m
@khokon_m 7 ай бұрын
Hey, great work. is there any way to replicate the eval functionality on MV3? So that I can allow users to inject their own code into a webpage? Thanks in Advance.
@RustyZone
@RustyZone 7 ай бұрын
Sounds like the user scripts api might be what you need although this requires the user to enable developer mode for the scripts to be used: kzbin.info/www/bejne/fZDGpqtsYrSCY6M
@joshuajaydan
@joshuajaydan Жыл бұрын
Manifest v3 example starts at 6:57
@lnsinfotechsolution3016
@lnsinfotechsolution3016 2 жыл бұрын
How to change ads with my photos and text.
@petratrading2741
@petratrading2741 2 жыл бұрын
I hope someone can help me, I want a code that highlight specific words in a page. I suck at coding. FYI, this code will be used to safe lives, so please help me
@TaprobanaOrg
@TaprobanaOrg Жыл бұрын
💙💙
@JonthueMichel-ul3mc
@JonthueMichel-ul3mc 4 ай бұрын
The source code is empty :(
@danihussain3651
@danihussain3651 Ай бұрын
8:50
@spirobel
@spirobel 2 жыл бұрын
i hate google so much for destroying the browser with their mv3 trash. brave also seems flaky on supporting mv2. we need to do something or we will be stuck with firefox
@paraggiradkar1022
@paraggiradkar1022 Жыл бұрын
can anyone tell me instead of chrome.extension.getBackgroundPage() what should I use in manifest version 3.
@RustyZone
@RustyZone Жыл бұрын
Background pages have been removed in mv3 so this method is not a like for like replacement. In what way do you currently use this? as it would depend on your use case to suggest an alternative
@alibarati6998
@alibarati6998 Жыл бұрын
Hi Hi teacher, this background.js file is in the version 2 manifest, can you tell me what it is in the version 3 manifest??? ------------------------------------------------------------------------------ var content = document.createElement("script"); content.src = chrome.extension.getURL("content.js"); content.onload = function() { this.parentNode.removeChild(this) }; (document.head || document.documentElement).appendChild(content);
@RustyZone
@RustyZone Жыл бұрын
Mv3 example should start around 6:52 in this video
@alibarati6998
@alibarati6998 Жыл бұрын
@@RustyZone I watched the video 10 times but my problem was not solved, please help me
@lumerial
@lumerial Жыл бұрын
Hey Rusty, the example is pretty neat, but it inserts text only, and I'm having a bit of trouble with the images now. I'm using manifest v3, and I'm trying to insert the image, here's the code of my content.js: //--- const img = document.createElement("img"); img.src = chrome.runtime.getURL("image.jpg"); document.body.appendChild(img); //--- What ends up happening is that the is inserted, but the image itself is not loaded (even though the URL is correct, I right-click the image and click 'open in new tab', and I see a URL like chrome-extension://iflghkbjoelhndpeaebmbcmdodhdcmon/image.jpg where the image is showing properly), and I get the error "GET chrome-extension://invalid/ net::ERR_FAILED". I already have "permissions": ["activeTab", "scripting"], "host_permissions": [""],... in my manifest.json, not sure what else I can do in that regard. I also tried to debug it with ChatGPT, it offered me some large xhr code to fix the issue, but it still gets the same "GET chrome-extension://invalid/ net::ERR_FAILED" error at xhr.send() line... So I'm really at a loss here. A seemingly simple thing, to insert an image with chrome extension, and I can't achieve even that :( Maybe you have any insights on how it can be done? Thank you for your time, and cheers!
@RustyZone
@RustyZone 10 ай бұрын
It sounds like you need to add your image path into your manifest web accessible resources: developer.chrome.com/docs/extensions/mv3/manifest/web_accessible_resources/
@lumerial
@lumerial 10 ай бұрын
@@RustyZone Thanks, that worked! I added "web_accessible_resources": [{ "resources": ["/image.jpg"], "matches": [""] }], to my manifest.json, and the image now shows up properly. I remember ChatGPT saying something among the lines that web_accessible_resources no longer exists in v3... That electronic bastard lied to me D; And oh well, back then I ended up recreating the image with css instead, because it was a simple icon. Thank you very much for the answer, and maybe it would also help others in the future~ Have a good one, Rusty!
@RustyZone
@RustyZone 10 ай бұрын
Ahh nice ChatGPT hasn’t replaced me just yet 😅
11.3: Chrome Extensions: Content Scripts - Programming with Text
16:55
The Coding Train
Рет қаралды 224 М.
The day of the sea 🌊 🤣❤️ #demariki
00:22
Demariki
Рет қаралды 72 МЛН
Full Tutorial | Building a Chrome Extension in Typescript and Vite
32:58
11.4: Chrome Extensions: Background Scripts - Programming with Text
16:20
The Coding Train
Рет қаралды 156 М.
Full Chrome Extension Crash Course For Beginners
1:00:20
Web Dev With Ron
Рет қаралды 3,3 М.