简体   繁体   中英

How to effect website using chrome extensions

Hi i've been looking at lots of tutorials and can't find anything it might be my poor google skills but I hoped the answer was quick and simple.

The Plan

The aim is to make an extension which will append any website using javascript.

Current State

I current have the javascript append coded and basic manifesto created

document.body.innerHTML += '<div id="adBar" style="background-color: #933131; width: 150px; height: 400px; position: fixed; left: 10px; top: 25%;"></div>'

The Problem

I can't find anywhere how to create a chrome extension which would allow this script to run in the background on every page, I can only find how to make a pop-up on click.

I hope this is clear and simple. All help is appreciated!

You can wrap the code in content scripts and use "all_urls" for match patterns.

manifest.json

{
  "name": "Test",
  "version": "1.0",
  "description": "Test",
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ],
      "run_at": "document_end",
      "all_frames": true
    }
  ],
  "manifest_version": 2
}

content.js

document.body.innerHTML += '<div id="adBar" style="background-color: #933131; width: 150px; height: 400px; position: fixed; left: 10px; top: 25%;"></div>'

You need to set matches to <all_urls> (also you can add a button to the extension to trigger it). Here is my full example:

Extension Buttons

My Extension
├── manifest.json
├── background.js
├── content.js
├── jquery-2.2.0.min.js
├── icon.png

manifest.json

{
    "manifest_version": 2,
    "name": "My Extension",
    "version": "0.1",
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": ["jquery-2.2.0.min.js","content.js"]
        }
    ],
    "browser_action": {
        "default_icon": "icon.png"
    },
    "background": {
      "scripts": ["background.js"]
    },
    "icons": {
        "16": "icon.png",
        "48": "icon.png",
        "128": "icon.png" 
    }
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
  // Send a message to the active tab
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

content.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if( request.message === "clicked_browser_action" ) {

        //YOUR CODE GOES HERE

    }
  }
);

Basically I added a button to the extension that calls the content.js once it is pressed. The listener is on background.js .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM