2

I am using Method 1 described here

Insert code into the page context using a content script

which is based on

Google Chrome "Application Shortcut": How to auto-load JavaScript?

This was working fine but after my browser (Chrome) updated to v71 this does not work anymore as my elements can't find the functions in my injected JS file anymore. I prepared an easy example:

manifest.json

   {
  "manifest_version": 2,
  "name": "Test",
  "version": "1.0.0",
     "web_accessible_resources": 
                [
                    "Callbacks.js"
                ],  
  "content_scripts": [
    {
        "matches": ["https://stackoverflow.com/"], 
        "js": ["inject.js"],
        "run_at": "document_idle"
    }
  ],
  "permissions": [
    "activeTab"
  ]
}

inject.js

function newButton(id, cb) 
{
    var b = document.createElement("div");
    b.setAttribute("onclick",cb);
    b.style.margin = "50px"
    b.style.width = "100px";
    b.style.height = "100px";   
    b.style.background = "gray";
    b.style.zIndex = 10000000;
    b.style.position = "absolute";
    b.id = id;  
    return b;
}

    var cc= document.createElement("script");
    cc.src =  chrome.runtime.getURL('Callbacks.js') ;
    document.body.appendChild(cc);

    document.body.appendChild(newButton("myId", "myfun();"));

Callbacks.js

function myfun(){
    window.alert("hallo");
}

When going on stackoverflow.com and clicking on the gray div I see this in my console

(index):1 Uncaught ReferenceError: myfun is not defined at HTMLDivElement.onclick ((index):1) onclick @ (index):1

However, I can still call myfun from the console directly.

Any ideas about this? With older Chrome version this still works.

Peter Hans
  • 73
  • 6
  • 2
    https://crbug.com/912069 – wOxxOm Dec 05 '18 at 12:24
  • Until this is fixed you'll have to create the element inside your page-level script (Callbacks.js). – wOxxOm Dec 05 '18 at 13:06
  • In my actual application I make API calls like chrome.runtime.getURL which will not work on the page level, right? I would need to somehow transfer these variables (results from the call to the API functions) from the content script into the page level script. Any good idea for that? – Peter Hans Dec 05 '18 at 13:13
  • You can use [custom events](https://stackoverflow.com/a/26740141/934239) for communication. (there's a chain of linked questions with more details / solutions) – Xan Dec 05 '18 at 13:25
  • 1
    You can put the code into a string and modify it to pass the variables via JSON.stringify, then get them via JSON.parse inside. The string should be assigned to scriptElement.textContent, of course. – wOxxOm Dec 05 '18 at 13:27
  • @wOxxOm Thank you for all the input. With the changes, my actual extension is working fine again. When you leave a post I can mark this thread as answered – Peter Hans Dec 06 '18 at 07:05

1 Answers1

-1

Restructured as mentioned by @wOxxOm which works fine now.

Peter Hans
  • 73
  • 6