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>
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.