【问题标题】:Chrome V71 breaks Extension JS injection?Chrome V71 打破了扩展 JS 注入?
【发布时间】:2018-12-05 11:49:47
【问题描述】:

我正在使用这里描述的方法 1

Insert code into the page context using a content script

基于

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

这工作正常,但在我的浏览器 (Chrome) 更新到 v71 后,这不再工作,因为我的元素在我注入的 JS 文件中找不到函数了。我准备了一个简单的例子:

ma​​nifest.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");
}

访问 stackoverflow.com 并单击灰色 div 时,我会在控制台中看到此内容

(index):1 Uncaught ReferenceError: myfun is not defined 在 HTMLDivElement.onclick ((index):1) onclick@(索引):1

但是,我仍然可以直接从控制台调用 myfun。

对此有什么想法吗?对于旧版 Chrome,这仍然有效。

【问题讨论】:

  • 在解决此问题之前,您必须在页面级脚本 (Callbacks.js) 中创建元素。
  • 在我的实际应用程序中,我进行了像 chrome.runtime.getURL 这样的 API 调用,这在页面级别上不起作用,对吧?我需要以某种方式将这些变量(调用 API 函数的结果)从内容脚本转移到页面级脚本中。有什么好主意吗?
  • 您可以使用custom events进行交流。 (有一连串的链接问题,其中包含更多详细信息/解决方案)
  • 你可以把代码变成一个字符串,修改它通过JSON.stringify传递变量,然后通过JSON.parse里面得到。当然,该字符串应该分配给 scriptElement.textContent。

标签: javascript google-chrome-extension


【解决方案1】:

按照@wOxxOm 所述进行了重组,现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多