Chrome-扩展:从background.js向content.js发送消息时出错

Chrome - Extension: Error when sending messages from background.js to content.js

本文关键字:js 消息 出错 content 扩展 background Chrome-      更新时间:2023-09-26

我的chrome扩展执行以下操作:

1)当用户单击应用程序的图标时,将触发一个新的弹出页面,其中有3个字段需要完成。

2)当按下提交按钮时,将调用getBackgroundPage(),并将输入值存储在background.js中。

3)我想在将这些值存储在后台后,以某种方式在内容脚本中使用这些值。我知道每个选项卡都是一个新的过程,它们之间的消息发送有点棘手,而且是异步完成的,但应该有一种简单的方法来完成。如果你有可行的解决方案,请尽可能清楚地说明!

这是代码:

Manifest.js

{
  "name": "My Extension",
  "version": "1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icon.png"
  },
  "background": {
      "scripts": ["background.js"],
      "persistent": false
  },
  "permissions": [
    "tabs", "<all_urls>","storage" , "activeTab"
    ],
"content_scripts": [
    {
      "matches": [ "https://www.linkedin.com/*"],
      "js": ["userInfo.js"]
  }] 
}

Background.js

chrome.browserAction.onClicked.addListener(function(tab) {
      { 
        chrome.tabs.create({
            url: chrome.extension.getURL('dialog.html'),
            active: false
        }, function(tab) {
            localStorage["tabid"]=tab.id;
            chrome.windows.create({
                tabId: tab.id,
                type: 'popup',
                focused: true,
                height: 350, width:400
            });
        });
    }
     return true;
});


function setCredentials(username,password,token) {
    console.log(username);
    console.log(password);
    console.log(token);

{  
    chrome.tabs.executeScript( parseInt(localStorage.tabid), {
        file: "userInfo.js"
    }, function() {
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
        }
    });
    }

};

Dialog.js

document.forms[0].onsubmit = function(e) {
    e.preventDefault(); // Prevent submission
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var token= document.getElementById('token').value;
    chrome.runtime.getBackgroundPage(function(bgWindow) {
        bgWindow.setCredentials(username,password,token);
        window.close();     // Close dialog
    });
};

userInfo.js

 alert("got it");

Dialog.html

 <!DOCTYPE html>
 <html>   
   <head> 
    <style> 
      #leadinformation { text-align: left; font: 16px; position :absolute; padding:20px 20px 20px 20px; } 
       #formwrapper {padding:10px 20px 20px 20px; width:200px;}
       #formsubmit {padding:0px 20px 20px 25px;}
      leadinformation input{ position:relative;}
      #ok { position: relative; top: 30%;  font-family: Arial;font-weight: bold; font-size: 13px; color: #ffffff; padding: 5px 5px 5px 5px;background-image: webkit-linear-gradient(top, #287bbc 0%,#23639a 100%);background-color: #287bbc; border-width: 1px; border-style: solid; border-radius: 3px 3px 3px 3px; boder-color: #1b5480; width: 160px; height: 35px;} 
      #titleParagraph {font-weight:bold; font-size:20px;} 
    </style>  
  </head> 
   <body> 

        <div id="leadinformation"> 
          <p id="titleParagraph">Provide your Salesforce login information!</p> 
          <form>
            <div id="formwrapper">
               Username: <input id="username" type="username">
               Password: <input id="password" type="password">
               Security Token: <input id="token" type="token">
             </div>
             <div id="formsubmit">
                <input id="ok" type="submit" value="OK">
             </div>
          </form>
            <script src="dialog.js"></script>
        <div> 

     </div> 
    </body> 
   </html>  

单击"确定"按钮后,将在后台控制台中写入用户名、密码和令牌,然后出现此错误。

无法访问url的内容"铬-extension://di***cb/dialog.html".

扩展清单必须请求访问此的权限主办(匿名函数)@background.js:39target。(匿名function)@扩展::SafeBuiltins:19safeCallbackApply@扩展::sendRequest:21handleResponse@扩展::sendRequest:72

因此,我想要实现的功能非常简单,用户单击图标->午餐弹出菜单-->键入信息-->接受-->在内容脚本中进一步使用信息

我找到了一种使用localStorage的方法:

background.js中,我添加了一个onMessage侦听器来与我的内容脚本对话

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['username']});
    else
      sendResponse({}); // snub them.
});

并且我在setCredentials()方法中使用localStorage

function setCredentials(username,password,token) {
     localStorage['username']=username;
}

userInfo.js中,每次为用户单击"确定"按钮时更新的localStorage值加载页面时,我都会请求后台。

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

现在,我可以在内容脚本中的任何位置使用localStorage中的这些值:D