1

I have a Chrome Extension that is injecting HTML/CSS into Google search pages from the Content Script.

Currently, I'm doing this using insertAdjacentHTML() and a long single string of HTML.

Relevant code snippets:

const chosenElements = document.getElementsByClassName('r');

for (var i = 0; i < chosenElements.length; i++) {
    chosenElements[i].insertAdjacentHTML('afterbegin', createHTML(name));
}

function createHTML(name) {
  return (
    '<a style="display: flex; justify-content: center; .... font-weight: 500;" href="https://www.mywebsite.com/">Click here to go to ' +
    name +
    ' website</a>'
  );

This does the right thing, and adds the HTML/CSS to the page, but is a pretty impractical method of doing this for me, as I want to greatly expand the HTML and CSS of the injected content, and doing so in one big line like this isn't going to really work.

Is there a better method of doing this injection?

Thinking of something like linking to a separate HTML file that has its own CSS file styling, or something similar.

Thanks.

0

1 Answer 1

1

Check out template strings. They're pretty well supported across the board (Can I use), and 100% supported in Chrome.

This uses backtick characters instead of quotes or single quotes to create a string, along with easy interpolation.

function createHTML(name) {
  return (
    '<a style="display: flex; justify-content: center; .... font-weight: 500;" href="https://www.mywebsite.com/">Click here to go to ' +
    name +
    ' website</a>'
);

becomes

function createHTML(name) {
  return (
    `<a style="display: flex; justify-content: center; font-weight: 500;"
        href="https://www.mywebsite.com/">
       Click here to go to ${name} website
     </a>` 
);

You'll still have all your code in a single file, but it'll be much easier to grok. Hope that helps!

Sign up to request clarification or add additional context in comments.

4 Comments

Ah yes I keep forgetting to use template strings, have swapped to using them instead of using the single quotes, thanks. Is this the only way to do it then do you think? No way of using a separate HTML file?
@chivs688 I can't think of a good way to use a separate HTML file. You might try splitting up your JS files into "template" files and including multiple <script src> tags, or if you're using something like Webpack, using imports.
@ I've just been playing with using an iframe to load a local html file, and it seems to have worked!
@chivs688 I mean sure, you could also do a fetch or XHR request to code split (I think, should work in Chrome extensions), but I wouldn't necessarily recommend it. There's nothing really wrong, just the extra requests. Iframe works the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.