Digital Pain
Digital Pain

Reputation: 37

Connect from popup.html to background.js script in Chrome Extension

Connect from popup.html to background.js script in Chrome Extension. When I click on the button, I want the background script to open a new tab.

Background Script:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {    
    if (message == "output") {

       var win = window.open('https://www.google.ca/webhp?hl=en&sa=X&ved=0ahUKEwjesaKd26TcAhWNw4MKHcN-CwgQPAgD', '_blank');
       win.focus();    
    }    
});

HTML:

<body>
    <script src="next.js"></script> 
    <input id="output" type="button" value="Go To Alternative Forum"/>
</body> 

Next:

 document.getElementById("output").addEventListener(("click"),function(){

        chrome.runtime.sendMessage("output"); 
});

Upvotes: 0

Views: 3008

Answers (2)

Abdul Jabbar
Abdul Jabbar

Reputation: 414

You can do that by window.open.

But if you want to do connect your html to background.js, then the official way is to send the message from your script next.js to the background.js and then background.js will create new tab to open the link.

Following code will work in your case:

next.js

 document.getElementById("next").addEventListener("click",function(){

        chrome.runtime.sendMessage({type: "openTab",value:code},function(response) {

        });

    });

popup.html

<body>
    <script src="next.js"></script>
    <input id="next" type="button" value="Go to google" />
</body>

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

    if (request.type == "openTab") {

        chrome.tabs.create({"url": "http://www.google.com", "selected": true}, function (tab) {

        });

    }

});

Upvotes: 2

user9085934
user9085934

Reputation:

Your script reference in your code should have a src="" attribute instead of a href="". Example here:

HTML:

<body>
    <script src="next.js"></script>
    <input onclick="start();" type="button" value="Go to google" />
</body>

next.js:

function start() {
    var win = window.open('https://www.google.ca/webhp?hl=en&sa=X&ved=0ahUKEwjesaKd26TcAhWNw4MKHcN-//CwgQPAgD', '_blank');
    win.focus();
}

Upvotes: 1

Related Questions