简体   繁体   中英

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

My chrome-extension does the following:

1) When the user click the app's icon a new popup page is being triggered with 3 fields to complete.

2) When the submit button is being pressed a getBackgroundPage() is being invoked and the input values are being stored inside background.js.

3) I want somehow to use this values inside my content script after they are being stored inside background. I know that each tab is a new process and the message sending between those is a bit tricky and is being done asynchronously but there should be an easy way to do it. Please if you do have a viable solution make it as clear as possible!

Here is the code:

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>  

After clicking the OK button the username, password and token are being written inside the background console followed by this error.

Cannot access contents of url "chrome-extension://di***cb/dialog.html".

Extension manifest must request permission to access this host.(anonymous function) @ background.js:39target.(anonymous function) @ extensions::SafeBuiltins:19safeCallbackApply @ extensions::sendRequest:21handleResponse @ extensions::sendRequest:72

So the functionality that I want to achieve is quite simple, user clicks icon -> lunch popup --> type information --> accept --> use the information further in the content script .

I found a way around it using localStorage:

in background.js I add a onMessage listener to talk to my content script

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

and I use localStorage inside the setCredentials() method

function setCredentials(username,password,token) {

     localStorage['username']=username;
}

in userInfo.js I request the background every time a page is loaded for the localStorage value that has been updated when the user clicked the "Ok" button.

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

Now I can use this values from localStorage anywhere I want inside my content script :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM