0

I want to send message from background.js to Content.js of Another tab.

Expected flow that I want.

Page1_Content.js --> Background.js --> Page2_Content.js

Is it possible? if yes then how?

A code snippet of background JS.

function sendMessagetoNewTab(tabURL){
      chrome.tabs.query({}, function(tabs) {
      //console.log("sendMessagetoNewTab tabs::::"+JSON.stringify(tabs));
      tabs.forEach(function(entry) {

    if(((entry.pendingUrl===tabURL)||(entry.url===tabURL))){
        console.log("Selected:::"+entry.selected+"::::active:::"+entry.active+":::::forEach tab::::"+JSON.stringify(entry));
    try{
    chrome.tabs.sendMessage(entry.id, {type: "openWindow", xpath: xpath, higlight: true},{},function(message, sender, sendResponse){
        debugger;
        console.log("chrome.tabs.sendMessage sender:::"+JSON.stringify(sender));
        console.log("chrome.tabs.sendMessage message:::"+JSON.stringify(xpath));
        console.log("chrome.tabs.sendMessage sendResponseMain:::"+JSON.stringify(sendResponse));
    });

    }catch(e){
        console.log("Exception::::"+e);
    }
    }
    });
  });
}

function openTabNew(xpath){
    //debugger;
                        var w = 380;
                    var h = 680;
                    var left = (screen.width/1)-(w/1);
                    var top = (screen.height/4)-(h/2);
                    chromeRunTimeId=chrome.runtime.id
                    if(localStorage.getItem("tabId")){
                        chrome.tabs.create({ url: chrome.extension.getURL('landing.html'), active: true }, function(tab) { chrome.windows.create({ tabId: tab.id, type: 'popup', 'width': w, 'height': h, 'left': left, 'top': top, focused: true }) });
                        localStorage.removeItem("tabId");
                    }else{
                        chrome.tabs.create({ url: chrome.extension.getURL('landing.html'), active: true }, function(tab) { chrome.windows.create({ tabId: tab.id, type: 'popup', 'width': w, 'height': h, 'left': left, 'top': top, focused: true }) });
                    }
                    sendMessagetoNewTab(xpath);

}
chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) {
        switch(message.type) { 
            case "openWindow":
            openTabNew(message.xpath);
                console.log(">>>>>>>>>>>>>>>>>>>>>>>>> BACKGROUND.JS openWindow::::::"+message.xpath);
                //closeExtraTabs();
                break;
            case "optq_reset_beforeunload":
                localStorage.clear();
                console.log(">>>>>>>>>>>>>>>>>>>>>>>>> BACKGROUND.JS optq_reset_beforeunload::::::"+message.xpath);
                break;
            default:
        }
    }
);

manifest.json

{
  "name": "Add Assertion",
  "version": "1.0",
   "author":"Shailesh Singh",
   "background": { "scripts": ["background.js"],"persistent": false},
  "description": "This Chrome extension Helps to Capture XPath for Users", 
  "manifest_version": 2,
  "content_security_policy": "script-src 'self' http://localhost chrome-extension://ahnjchloffmlcoipmlflaaggopgdgojp ; object-src 'self'",
 "permissions": ["http://localhost/*",
    "https://elevate-dev1.optimizeq.com/","declarativeContent","tabs","storage","notifications","contextMenus","activeTab", "file:///*","http://*/","https://*/","<all_urls>"],
"web_accessible_resources": [
    "images/*.png",
    "css/inner.css",
    "landing.js",
    "js/*",
    "locales/*"
  ],
  "incognito": "split",
  "offline_enabled": true,
  "browser_action":{"default_icon":"square.png","default_popup":"landing.html","browser_style": true},
  "content_scripts": [{
  "run_at": "document_end",
  "all_frames": true,
  "match_about_blank":true,
        "matches": [
            "http://*/*",
            "https://*/*"       
            ],
        "js": ["jquery-3.4.1.js","content.js"],
        "run_at": "document_end"
        }],

  "externally_connectable": {"matches": ["https://*.chrome.com/*","https://wwww.google.com/*","https://wwww.facebook.com/*"]},
  "chrome_url_overrides": {"bookmarks": "landing.html"},

    "icons": {"128": "square.png","64": "square.png","32": "square.png","16": "square.png"}
}

Content.js Snippet only

var newWindow;
    function checkAndSendRequest(elem,responseObj){

        if(typeof elem!=='undefined'&&responseObj&&responseObj.targetPageId&&(window.location.href.indexOf("localhost")!=-1||window.location.href.indexOf("elevate")!=-1)){
            projectId=localStorage.getItem("project_id");
            exeId=localStorage.getItem("exeId");
            xpath=getElementXPath(elem);

            newWindow=window.open(responseObj.pageUrl, "_blank");
            //opening new tab here aka Page2

            window.resizeTo(window.outerWidth-500,window.outerHeight);

            sendDetailsToBG_Step2(xpath,projectId,responseObj.targetPageId,exeId,responseObj.highlight,responseObj.pageUrl);
            }
    }

    function sendDataToBackgroundJs_Step1(xpath,event){
        mouseX = Math.round (event.clientX);
        mouseY = Math.round (event.clientY);
        var elem = document.elementFromPoint(mouseX, mouseY);
        var url='';
        var targetPageId;
        var title='';
        var flags=false;
        var responseObj;
        //debugger;
        if(elem!='null'&&elem){
        if(elem.tagName=="circle"){
            showAnimation=false;
            responseObj=getData(elem.parentElement,0);
            checkAndSendRequest(elem,responseObj);

        }else if(elem.tagName=="g"){
            if(elem.tagName=='g'&&elem.classList.contains('node')){
                showAnimation=false;
                responseObj=getData(elem.firstElementChild,0);
                checkAndSendRequest(elem,responseObj);
            }
        }else{
            //debugger;
            console.log("click inside circular area properly....");
        }
        }else{
            console.log("click inside circular area properly.");
        }

    }



function getData(elem){
        var returnObj={};

            $(elem.childNodes).each(function(i, item) {
                if(item.classList.contains('targetPageId')){
                    var targetPageId =parseInt(item.textContent);
                    returnObj.targetPageId=targetPageId;
                }else if(item.classList.contains('treeUrl')){
                    var pageUrl=item.textContent;
                    returnObj.pageUrl=pageUrl;
                }else if(item.classList.contains('treeTitle')){
                    var pageTitle=item.textContent;
                    returnObj.pageTitle=pageTitle;
                }
        });
        returnObj.highlight=true;
        return returnObj;
}

    function sendDetailsToBG_Step2(xpath,projectId,targetPageId,exeId,highlight,pageUrl){
        //debugger;
    var loginres=JSON.parse(localStorage.getItem('STORAGE_LOGIN_RES'));
    var token=loginres.token;
    var prefix=loginres.type;
    var serverName=window.location.origin;
     serverName="http://localhost:8080";
    //serverName=serverName+"/v2/";

        localStorage.setItem("projectId",projectId);
        localStorage.setItem("exeId",exeId);
                if(typeof chrome.app!=='undefined'){
                if(typeof chrome.app.isInstalled!=='undefined'){
                var object={'type': "openWindow", 'xpath': xpath, 'prefix': prefix, 'token': token, 'projectId': projectId, 'exeId': exeId, 'targetPageId': targetPageId,'serverName':serverName,'highlight':highlight,'pageUrl':pageUrl};
                //var object={'type': "setXPathNew", 'projectId': projectId};
                chrome.runtime.sendMessage(object);
                }else{
                    reloadPage(extensionId);
                    }
                }else{
                    //reloadPage(extensionId);
                    }
    }

    function reloadPage(extensionId){
        debugger;
        try{
            chrome.runtime.connect(extensionId);
        }catch(e){
            console.log("reloadPage:::"+e);
            var r = confirm("disconnected Please Refresh the Page \n Press OK TO Refresh Page.");
          if (r) {
            window.location.reload(true);
          } 

        }
    }
ThinkTank
  • 1,737
  • 5
  • 22
  • 36
  • It's unclear what the problem is. I don't see how you create that "new tab", I also don't see how it's related to "send to the same Page where it has been initiated". Maybe [this answer](https://stackoverflow.com/a/54715122) could help you. – wOxxOm May 23 '20 at 11:07
  • I need to send data from page1_ContentJS ---> background JS ---->Page2ContentJS IMP: Page2 is not PopupJS I have done from page1 to Background back and forth. Now I want to send data some other tab. – ThinkTank May 23 '20 at 15:03
  • It's still unclear what the problem is. To send a message you need a tab id - you know that. I guess the problem is how to find the id? But that depends on how that other tab is identified or created and I don't know see that in the question. – wOxxOm May 23 '20 at 15:15
  • I am getting tab Id here if you see code but still it sends data to same Page1_content.js – ThinkTank May 23 '20 at 15:23
  • It means you code is incorrect but I can't help without more info. There's no magic trick in the API. – wOxxOm May 23 '20 at 15:28
  • what part strategy wise or basic code wise – ThinkTank May 23 '20 at 15:29
  • It's really something that should be easy to debug: since you're sending to the same tab the only explanation is that your code incorrectly chooses this tab. There are no other explanations based on the fragment of code you've shown. – wOxxOm May 23 '20 at 15:36
  • one little help how do i find and verify tabId anything on that will be helpful – ThinkTank May 23 '20 at 15:39
  • I don't understand. You're already finding it using chrome.tabs.query and `if` check. I don't think I can help here. – wOxxOm May 23 '20 at 15:41
  • yes but it sending message to page1_content.js where as I want to send to some other Tab i.e. Page2_content.js – ThinkTank May 23 '20 at 15:44
  • Any other way to verify it whether I'm doing it right way with right tabId – ThinkTank May 23 '20 at 15:45
  • Use devtools debugger to inspect `tabs`. – wOxxOm May 23 '20 at 15:46
  • Using devtools debugger should help you see the difference between the correct tab and the incorrect tab. Then you can think of a way to add a check for that. This is the best advice I can give since you didn't show any more info I asked. – wOxxOm May 23 '20 at 15:54
  • Here is tabeInfo by debug `{ "active": false, "audible": false, "autoDiscardable": true, "discarded": false, "height": 947, "highlighted": false, "id": 291, "incognito": false, "index": 6, "mutedInfo": { "muted": false }, "openerTabId": 24, "pendingUrl": "https://www.yummytiffins.com/welcome/concept", "pinned": false, "selected": false, "status": "loading", "title": "", "url": "", "width": 1920, "windowId": 18 }` – ThinkTank May 23 '20 at 16:04
  • It's you who should inspect it, not me. I can give you one more guess though: if sendMessagetoNewTab is called from onMessage listener then you can pass sender.tab.id as a second parameter and use it to skip this tab in `if` check for the URL. Anyway, guessing is the wrong and inefficient approach so unless you provide more info I won't be able to help you further. – wOxxOm May 23 '20 at 16:09
  • which kind of info? can you be more specific on that – ThinkTank May 23 '20 at 16:13
  • As I said in my first comment, I don't see how you create that "new tab". I also don't see how the code you've shown is invoked. This is what constitutes an [MCVE](/help/mcve). Adding manifest.json is often helpful as well. – wOxxOm May 23 '20 at 16:57
  • Hi @wOxxOm I have added details which you have mentioned if anything is left let me know please. – ThinkTank May 24 '20 at 15:44
  • Remove sendMessagetoNewTab call and simply do chrome.tabs.sendMessage inside the callback of chrome.tabs.create - it already gives you the new tab and its id. Overall the code seems over-complicated, I believe you can simplify it, see [example 4 in this answer](https://stackoverflow.com/a/54715122). – wOxxOm May 24 '20 at 16:09

0 Answers0