Josh Hicks
Josh Hicks

Reputation: 1

Can't get the script to execute, chrome message passing error?

I'm trying to finish up this chrome extension I've been working on but I just got stuck.

Basically I'm trying to get the script to be executed when enabled by the user (by clicking an on and off switch I put in the popup window). Either I'm missing some code, or my chrome message passing is wonky at some point so popup cant communicate with content.

I'm a beginner, this is the first thing I've ever written, so any help will be greatly appreciated.

Here's the code, let me know if you need to see anything else

script.js

    var audio = new Audio("http://a.tumblr.com/tumblr_libwsrXYlA1qbma2vo1.mp3"),
    timer = null,
    isScrolling = false;


function enable() {
    $(window).on('scroll', function () {
        clearTimeout(timer);
        audio.play();
        if (!isScrolling) {
            isScrolling = true;
            setTimeout(function () {
                audio.pause();
                isScrolling = false;
            }, 600);
        }
    });
}

function disable() {
    $(window).off('scroll');
    if (!isScrolling) {
        isScrolling = true;
        setTimeout(function () {
            audio.pause();
            isScrolling = false;
        }, 600);
    }
}

chrome.tabs.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
        if (request.greeting == "hello") {
            enable();
        } else {
            disable();


        }
    }
);

popup.js

    $('#myonoffswitch').on('click', function (e) {
        if (e.target.checked) {
            console.log('enable');
        } else {
            console.log('disable');

        }

        chrome.tabs.sendMessage({greeting: "hello"}, function (response) {
            console.log(response.farewell);
        }); 
});

mypopup.html

<!doctype html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/mystyle.css" />
</head>

<body>

    <div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
    </div>

<script src="/data/script.js"></script>    
<script src="/data/jquery-2.1.3.js"></script>
<script src="popup.js"></script>

</body>

</html>

Upvotes: 0

Views: 58

Answers (1)

Xan
Xan

Reputation: 77502

Your code does never goes to the disable branch in the content script:

    if (request.greeting == "hello") {
        enable();
    } else {
        disable();
    }

You always send {greeting: "hello"} regardless of off/on state.

Upvotes: 1

Related Questions