首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Chrome扩展带来了两个错误:未登录的TypeError和未检查的runtime.lastError

Chrome扩展带来了两个错误:未登录的TypeError和未检查的runtime.lastError
EN

Stack Overflow用户
提问于 2022-02-26 01:20:37
回答 1查看 443关注 0票数 0

在我正在构建的Chrome扩展程序上,我面临两个错误:

错误1:

Uncaught :无法设置空(设置'onclick')上下文的属性_generated_background_page.html堆栈跟踪popup.js:3 (匿名函数)

错误2:

未检查的runtime.lastError:无法建立连接。接收端不存在。上下文_generated_background_page.html堆栈跟踪_generated_background_page.html:0 (匿名函数)

我已经检查了这个网站上解决这两个错误的问题,我尝试了他们提供的解决方案,但我仍然面临着这两个错误。

我的原始代码:-

popup.js (尝试将错误1从onclick改为onClicked,尝试将此代码放入window.onload中以避免错误2)

代码语言:javascript
运行
复制
let populateBtn = document.getElementById('populateBtn');
let textArea = document.getElementById('productList');
populateBtn.onclick = function(element) {
    let color = element.target.value;
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if(!textArea.value) 
        {
            chrome.tabs.executeScript(
                tabs[0].id,
                {code: 'alert("Please, populate the order list!");'});
            return;
        }
        chrome.tabs.sendMessage(tabs[0].id, {data: textArea.value.replace(/\t/g,'').split("\n")}, function(response) {
        });
    });
};

background.html (尝试将<script>放在错误1的</body>标记之后)

代码语言:javascript
运行
复制
<body>
    <p>Gina's Bakery Bulk Order</p>
    <textarea id="productList"></textarea>
    <button id="populateBtn">Create Order</button>
    <script src="popup.js"></script>
</body>

app.js (尝试了错误2的chrome.runtime.connect )

代码语言:javascript
运行
复制
chrome.runtime.onInstalled.addListener(function() {
});

inject.js (尝试了错误2的chrome.runtime.onConnect.addListener )

代码语言:javascript
运行
复制
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    let failed = [];
    request.data.forEach(element => { // itterate over all products
        if(element.includes('-')){
            let data = element.split('-');
            let quantity = data[0].toLowerCase().replace("gb", "").trim();
            let ID = data[1].trim();
            let elementName = 'pid_' + ID.replace(".", "_");
            if(document.getElementsByName(elementName).length > 0) 
                document.getElementsByName(elementName)[0].value = quantity;
            else        
                failed.push("<td>GB-"+ ID +"</td><td>" + quantity + "</td>");
        }
     });   
    if(failed.length > 0){
        //alert("Order unsuccessful! One or more products are not ordered: " + failed.join(", "));
        let modal = document.createElement("div");
        modal.setAttribute("id", "failedOrderModal");
        modal.setAttribute("style", "position:fixed;width:250px;left:50%;top:100px;background-color:#fff;border-radius:10px;padding:10px;z-index:10000;color:#000;border: 1px solid red;text-align:center;");
        let head = document.createElement("h2");
        head.innerText = "Order unsuccessful! One or more products were not found!";
        modal.appendChild(head);
        let table = document.createElement("table");
        let tbody = document.createElement("tbody");
        table.appendChild(tbody);
        let tr = document.createElement("tr");
        tr.innerHTML = "<td>ITEM</td><td>QTY</td>";
        tbody.appendChild(tr);
        failed.forEach(failedItem => {
            tr = document.createElement("tr");
            tr.innerHTML = failedItem;
            tbody.appendChild(tr);
        });
        modal.appendChild(table);
        let closeBtn = document.createElement("button");
        closeBtn.setAttribute("type", "button");
        closeBtn.innerText = "Close";
        closeBtn.onclick = function(){
            document.getElementById("failedOrderModal").remove();
        }
        modal.appendChild(closeBtn);
        document.body.appendChild(modal);
    }
    else
    {
        alert("All products were successfuly populated!");  
    }   
    sendResponse({result: "ok"})
    return true;
});

manifest.json

代码语言:javascript
运行
复制
{
    "name": "Gina's Bakery Order",
    "version": "1.0",
    "description": "Helps automate orders from ginas-bakery.com.au",
    "permissions": ["activeTab", "declarativeContent", "storage"],
    "background": {
        "scripts": ["app.js", "popup.js"],
        "persistent": false
      },
    "icons": {
        "16": "images/ginas-bakery_16.png",
        "32": "images/ginas-bakery_32.png",
        "48": "images/ginas-bakery_48.png",
        "128": "images/ginas-bakery_128.png"
      },
    "browser_action": {
        "default_popup": "background.html"
      },
      "content_scripts": [
        {
            "matches": ["*://www.ginas-bakery.com.au/order/"],
            "js": ["inject.js"]
        }
    ],
    "manifest_version": 2
}

上述任何一种解决办法都没有奏效。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-26 02:16:55

后台脚本页是一个不可见的隐藏页面,因此运行可见脚本(如app.js或popup.js )是没有意义的。从background中删除manifest.json部分,并在磁盘和manifest.json中将background.html重命名为popup.html。

manifest.json:

代码语言:javascript
运行
复制
{
  "name": "Gina's Bakery Order",
  "version": "1.0",
  "permissions": ["activeTab", "declarativeContent", "storage"],
  "browser_action": {"default_popup": "popup.html"},
  "manifest_version": 2
}

内容脚本只在页面加载时运行,所以如果您只是重新加载或安装/更新了扩展,而没有重新加载选项卡,内容脚本就不会在那里运行。

尽管您可以使用inject them explicitly,但最好按需使用编程注入(使用executeScript而不是content_scripts),因为在安装扩展时可以不需要任何主机权限。

popup.js:

代码语言:javascript
运行
复制
const textArea = document.getElementById('productList');
const btn = document.getElementById('populateBtn');
btn.onclick = () => {
  const data = textArea.value.replace(/\t/g, '').split('\n');
  chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
    chrome.tabs.sendMessage(tab.id, {data}, () => {
      if (chrome.runtime.lastError) {
        chrome.tabs.executeScript({file: 'inject.js'}, () => {
          chrome.tabs.sendMessage(tab.id, {data});
        });
      }
    });
  });
};

由于您没有在sendMessage中使用响应,所以首先不要发送它,即从inject.js中删除sendResponse({result: "ok"}); return true;

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71273331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档