Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content script loading in chrome extension

I have problem with developing chrome-extensions.

I have content script:

window.addEventListener("load",function(){
   var html = document.getElementsByTagName('html')[0];
   var title = document.getElementsByTagName('title')[0].innerHTML;
   if(html){
      chrome.extension.sendRequest({akce: 'content', title: title},function(response){});
      alert(title);
   }
},false);

then I have a BG page:

chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
    if(request.akce == 'content'){
        console.log(request.title);
    }
});

The problem is that when I start typing to address bar, my content script is loaded on the site which is first in autocomplete list. As you can see in the screenshot below, the content script is loaded before I hit enter in address bar and is loaded on the site where I am not yet.

I have no idea what is happening. Please, please help me.

screenshot

like image 784
tomash Avatar asked Oct 07 '22 16:10

tomash


1 Answers

Solution is injected script from background page.

Example: get referrer from bg page

chrome.tabs.executeScript(tabId,{
    code: "chrome.extension.sendRequest({action: 'content_refer', url: document.referrer},function(response){});"
});

chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
    if(request.action == 'content_refer'){
        wipstats.allPages[sender.tab.id].ref = request.url;
    }
});
like image 52
Lukas Sindler Avatar answered Oct 10 '22 04:10

Lukas Sindler