0

I am trying to get CodeMirror instance on the website then get the code inside in this Chrome extension.

My code works fine in Console.

enter image description here

However it does not work when I use these code in content script of my Chrome extension.

Here is my content script code:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {

    if (request.name == "GetChosenCodeMirrorText"){
     console.log("content script starts");
     var codeMirrorElementArray = document.getElementsByClassName("cm-s-default");
     
        Array.prototype.forEach.call(codeMirrorElementArray, function(codeMirrorElement){
            console.log(codeMirrorElement);
            var codeMirrorEditor = codeMirrorElement.CodeMirror;
            var line = codeMirrorEditor.getLine(1);
            console.log(line);
        });
     
     sendResponse({codeMirrorElementArray: "Just Testing"});
    }
  });

Here is my manifest.json

{
    "manifest_version": 2,
    "name": "xxx",
    "description": "xxx",
    "version": "1.0",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "index.html"
    },
    //always need an injection
    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            //"matches": ["://*/*"],
            "css": ["codemirror.css"],
            //"js": ["codemirror.js", "underscore.js", "content_script.js"],
            "js": ["codemirror.js", "content_script.js"],
            //"js": ["content_script.js"],
            "run_at": "document_end"
        }
    ],
    "permissions" : ["tabs"],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

enter image description here

And when I run this code, here is what I get from console:

Or is there a better way to get CodeMirror instance on a website?

halfer
  • 19,824
  • 17
  • 99
  • 186
Penguin Zhou
  • 131
  • 2
  • 10

0 Answers0