event listener doesn't work from a injected script

3,776 views
Skip to first unread message

Gopi Mullapudi

unread,
May 16, 2018, 10:01:57 AM5/16/18
to Chromium-Extensions-Announce
I inject a content script at runtime using below code 
chrome.tabs.executeScript(tabId, {file:"domScriptFile.js"});


And my domScriptFile.js has below content. instead of start listening to events all the time I want to wait for a command or message from the background script. So i introduced a function listenToClicks() which I would like to call to start listening for events upon receiving a runtime message.  But this function never captures the click events in the dom but my event listener which is at the beginning of the below code always works.  I tried using all the three run_at scopes document_start,document_end and document_idle to fix this issue, but it's never consistent and mostly it was not working. Any idea how to fix this?

 the listenToClicks() function can listen to the events on github.com page most of the time but fails for google.com or stackoverflow.com
And whenever listenToClicks work the stoplistenToClicks is not working to remove the listener.

//this code always works
document.addEventListener("click", function(event){       
    alert('i always work');          
});

// The below code doesn't work 
function listenToClicks(){
   document.addEventListener("click", function(event){       
      alert('click is fired');          
   });
}

// even The below code doesn't work 
function stopListenToClicks(){
   document.removeEventListener("click", function(event){       
      alert('click is fired');          
   });
}
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
      console.log("a request to start listending for click events");
      if(msg.command == "listen")
        listenToClicks();
     elseif(msg.command == "stoplisten")
        stopListenToClicks();
     sendResponse({msg: "click events are now fired"});
return true; });

PhistucK

unread,
May 16, 2018, 10:15:12 AM5/16/18
to Gopi Mullapudi, Chromium-extensions
Can you share the entire code of a minimal extension that reproduces the issue?

PhistucK


--
You received this message because you are subscribed to the Google Groups "Chromium-Extensions-Announce" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To post to this group, send email to chromium-...@chromium.org.
Visit this group at https://groups.google.com/a/chromium.org/group/chromium-extensions/.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/257b280e-fee7-4cdf-aa97-53c259135dd9%40chromium.org.
For more options, visit https://groups.google.com/a/chromium.org/d/optout.

Gopi Mullapudi

unread,
May 18, 2018, 1:12:42 PM5/18/18
to Chromium-Extensions-Announce, gkmul...@gmail.com
Sorry for the late.

Here is the code you requested for manifest.json. I have to click the extension icon twice to make the content script listenToClicks() function work. And also if user clicks any link within the same page, and page refreshes  then content script is lost. It doesn't recognize my angular framework, though it's out of scope for this question.

{
"name": "listen clicks",
"description": "Utility for capturing clicks",
"version": "0.3",
"permissions":[
"tabs","activeTab",
  "https://*/*",
  "http://*/*"
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Krishna Inspector",
  "default_popup": "popup.html"
},
"manifest_version": 2
}



contentscript.js:

//this code always works
document.addEventListener("click", function (event) {
alert('i always work.clicked');
});

// The below code doesn't work
function listenToClicks(targetDocument) {
console.log('cs: listenToClicks function is called');
targetDocument.addEventListener("click", function (event) {
alert('listenToClicks function: click event is fired');
});
}

// even The below code doesn't work
function stopListenToClicks() {
document.removeEventListener("click", function (event) {
alert('stopListenToClicks click is fired');
});
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log("cs: onMessage addListener is fired ",request);
if (request.subject == "listen"){
listenToClicks(document);
}
elseif(request.subject == "stoplisten")
stopListenToClicks();
sendResponse({ msg: "cs: click events are now fired from listentoclicks event is function" });
return true;
});

console.log("cs script loaded");





background.js:

var activeTabId = undefined;

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
activeTabId = tab.id;
console.log("bg: .onupdated.onClicked.", activeTabId);

});


console.log("bg loaded 6");

chrome.runtime.onMessage.addListener(function (msg, sender) {
console.log("bg onMessage received ", activeTabId,msg);
chrome.tabs.executeScript(activeTabId, { file: "csdom.js" }, function (response) {
console.log("bg :execute script Response from cs ", response);
});

// First, validate the message's structure
if (msg.subject === 'listen') {
// Enable the page-action for the requesting tab
console.log("bg: sending message listen to cs");
chrome.tabs.sendMessage(activeTabId,
{ 'from': 'popup', 'subject': 'listen' },
function (response) {
console.log('bg ' + response);
}
);
}

});



popup.html:



<!DOCTYPE html>
<html lang="en" ng-app="" ng-csp>
<script src="popup.js"></script>
<body>

<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>

</div>

</body>
</html>




popup.js:


// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', function () {
// ...query for the active tab...
console.log("cs: DOMContentLoaded fired");
//alert("cs: DOMContentLoaded");

chrome.runtime.sendMessage(
{ 'from': 'popup', 'subject': 'listen' },
function (response) {
console.log(response);
}
);
});

console.log("popup loaded");
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extensions+unsub...@chromium.org.

PhistucK

unread,
May 18, 2018, 2:15:23 PM5/18/18
to Gopi Mullapudi, Chromium-extensions
1. The Angular issue should be easily resolvable - inspect your popup (right click on the button and choose "Inspect popup" and you will see a content security policy error.
2. Since you are using executeScript when the user clicks, the navigation stops the execution of the script, You should subscribe to chrome.tabs.onUpdate and executeScript again if the tab URL has changed (other than in the hash - # - part) until you want to stop listening.
3. csdom.js does not exist, so executeScript fails. I changed it to contentscript.js.
4. contentscript.js has elseif instead of else if. I was surprised it did not complain about a syntax error, but then I realized, syntax-wise, it tries to call a function named elseif, hehe, which is totally legal (though it will still fail).
5. onMessage.addListener in contentscript.js does not work like you expect due to a race condition. In the background script, you executeScript, but you sendMessage immediately and not in the callback of executeScript, so contentscript.js finishes executing (and calling onMessage.addListener in order to start listening to messages) only after you already sent the message.



PhistucK


Sorry for the late.

To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.

--
You received this message because you are subscribed to the Google Groups "Chromium-Extensions-Announce" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
Reply all
Reply to author
Forward
0 new messages