0

I am creating a chrome extension and the content.js and background.js just won't communicate. I don't know what I am doing wrong. hellp.

manifest.json:

{
    "name": "Custom Redirects",
    "version": "1.0",
    "description": "Redirect a request on any webpage to another webpage of your choice",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ],

    "browser_action": {
        "default_popup": "extension.html",
        "default_title": "Custom Redirect"
    }

}

background.js:

var inputs = document.getElementsByTagName('input');
var form = document.getElementById('form');

form.addEventListener('submit', function() {
    alert('submiteed')
    var data = [inputs[0].value, inputs[2].value];
    chrome.runtime.sendMessage(data, function(response) {
        //
    })

}) 

content.js:

var url = window.location.href;
chrome.runtime.onMessage.addListener(function (request) {
    alert('message recieved');
});

extension.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Redirector</title>
    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

    <div class='header'>Custom Redirects<br><span style='font-size: 20px; color: gray'>Add New Link</span></div>
    <hr style='border: 1px solid green'>

    <form id='form'>
        <input type='text' value='' required></input>
        <input type='button' class='acBtn' value='Add Current URL'> 
        <input type='text' value='' required></input>
        <input type='button' class='acBtn' value='Add Current URL'>
        <input type='submit' class='addBtn' value='Create'>
    </form>
    <hr style='border: 1px solid green'>
    <button class='viewBtn'>View My Links</button>
    <script type="text/javascript" src='background.js'></script>

</body>

The alert function in content.js doesn't call so the message is not being sent, received, or both. pleas help me

  • Background scripts can't access the DOM. That's what content scripts are for. Therefore your submit event will never fire. – Mitya Jun 14 '20 at 17:38
  • 1) A proper background script should be declared in manifest.json and it runs in a separate hidden background page, see the documentation. You didn't declare it so your background.js is not a background script. 2) The problem here is your use of form. Don't use it or prevent the `submit` event, [example](https://stackoverflow.com/a/57274425). – wOxxOm Jun 14 '20 at 17:39
  • And don't use `alert` for debugging because it blocks execution thus breaking the messaging response. Use [the correct devtools](https://stackoverflow.com/a/38920982): one for the tab, another for the popup, then use breakpoints or console.log. – wOxxOm Jun 14 '20 at 17:52
  • @Utkanos The submit event is being fired because and alert will show inside the popup that says "submiteed". – Maxwell Warren Jun 14 '20 at 20:04

0 Answers0