0

So I've been struggling with passing "getVideo" from content.js (my content script) to popup.js. Right now I copied from https://developer.chrome.com/extensions/messaging just to try to get a message. However, as soon as the page opens, I get an error on the console: Cannot read property 'farewell' of undefined. I've tried every single suggestion/answer from every thread related to Chrome extension messaging with nothing working. This makes me believe I have something more wrong with how I have the extension set up, but I have no idea what. Thanks!

manifest.json

{
  "manifest_version": 2,

  "name": "JW Player Tools",
  "description": "This extension lets you speed up and download captions from a JW video",
  "version": "1.2.5",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "content_scripts": [
 {
   "matches": ["*://*.tower.la.utexas.edu/*"],
   "all_frames": true,
   "js": ["content.js"],
   "run_at": "document_idle"
 }]
}

popup.js

document.addEventListener('DOMContentLoaded', function() {


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



    var playback = document.getElementById('playback');
    playback.addEventListener('click', function() {
        var newspeed = prompt("Current Speed: " + getVideo.playbackRate + "\nNew Speed: ");
        getVideo.playbackRate = newspeed;
    });

    var captions = document.getElementById('captions');
    captions.addEventListener('click', function() {
        for (index = 0; index < getVideo.textTracks[0].cues.length; ++index) {
            document.write(getVideo.textTracks[0].cues[index].text + " ");
        }
    });
});

content.js

var waitForVideo = setInterval(checkForElement, 150);

function checkForElement() {
    var videoElem = document.getElementsByTagName('video');
    if (videoElem.length) {
        clearInterval(waitForVideo);
        var videolink = videoElem[0].getAttribute('src');
        getVideo = videoElem[0];



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




    }
}

popup.html

   <!doctype html>
    <html>
      <head>
        <title>JW Tools</title>
        <script src="popup.js"></script>
      </head>
      <body>
        <button id="playback">Speed Up</button>
        <button id="captions">Download Captions</button>
      </body>
   </html>
6
  • 1
    Please provide your popup.html and HTML for the web page on which you are testing this (or at least a URL).
    – Makyen
    Jan 26, 2017 at 7:27
  • 1
    It is a Bad Idea™ to use the name background.js as the name of your content script. It is too easy to confuse with it being a background script.
    – Makyen
    Jan 26, 2017 at 7:28
  • 2
    In your content script, getVideo is a DOM element. You will not be able to send it in a message. DOM elements are not JSON-serializable. All messages must be JSON-serializable. You don't actually show trying to send it as a message, but you say in your first sentence that it is what you are struggling with.
    – Makyen
    Jan 26, 2017 at 7:33
  • 1
    You don't need to pass the element itself, just the text data: extract it and send it. Also, you might need to use proper DOM manipulation or insertAdjacentHTML instead of document.write.
    – wOxxOm
    Jan 26, 2017 at 13:13
  • 1
    @umer936, We can advise, but as wOxxOm implied, part of that advice is you might only need some portion of the info that is contained within the DOM element you are wanting to message, which you can extract and message, or move processing into the content script. We don't know what you need from the element, so can't give detailed advice. However, assuming the code you have provided duplicates the problem described in the question (I have not yet tried it), getting that information is actually a different problem, and should be a separate Question. I'll try the code and comment again.
    – Makyen
    Jan 26, 2017 at 16:38

1 Answer 1

0

I fixed the problem. I moved the functions to content.js like so.

content.js

var waitForVideo = setInterval(checkForElement, 150);

function checkForElement() {
    var videoElem = document.getElementsByTagName('video');
    if (videoElem.length) {
        clearInterval(waitForVideo);
        getVideo = videoElem[0];
    }
}

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.task == "caption") {
        for (index = 0; index < getVideo.textTracks[0].cues.length; ++index) {
            document.write(getVideo.textTracks[0].cues[index].text + " ");
        }
    } else if (request.task == "speed") {
        var newspeed = prompt("Current Speed: " + getVideo.playbackRate + "\nNew Speed: ");
        getVideo.playbackRate = newspeed;
    } else {
        // sendResponse({});
    } 
});

and used popup.js to message content.js

document.addEventListener('DOMContentLoaded', function() {
    var playback = document.getElementById('playback');
    playback.addEventListener('click', function() {
        // var newspeed = prompt("Current Speed: " + getVideo.playbackRate + "\nNew Speed: ");
        // getVideo.playbackRate = newspeed;

        chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {
                task: "speed"
            }, function(response) {
                alert(response.farewell);
            });
        });

    });

    var captions = document.getElementById('captions');
    captions.addEventListener('click', function() {
        // for (index = 0; index < getVideo.textTracks[0].cues.length; ++index) {
        // document.write(getVideo.textTracks[0].cues[index].text + " ");
        // }

        chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {
                task: "caption"
            }, function(response) {
                alert(response.farewell);
            });
        });
    });
});

Thanks for the help! @Makyen @wOxxOm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.