I would like to open a new tab from within my popup.html by clicking a button contained in popup.html.
My approach is to send a message from popup.html to the eventPage.js which will then open the new tab when the message is received.
This however is not working. Please see the code below:
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src="popup.js"></script>
</head>
<body style="width:400px;">
<div id="content">
<div id="openTab"><button type="button" id="btnOpenTab" name="btnOpenTab" onclick="sendMessage()">Open New Tab</button></div>
</div>
</body>
</html>
eventPage.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse)
{
if (request.action == "openNewTab")
chrome.tabs.create({ url: request.url });
}
);
popup.js
function sendMessage()
{
chrome.extension.sendMessage({
action: "openNewTab",
url: "www.google.com"
});
}
manifest.json
{
"name": "Open new tab",
"version": "1.0",
"manifest_version": 2,
"description": "Opens new tab",
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
EDIT: Found an error message in console with this message:
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
The content security policy prevents you using JavaScript in your HTML (in this case, you are getting an error because of the onclick="sendMessage()"
in your popup.html
file.
You can get the desired result by removing the onclick
attribute from the button and instead adding the event listener in your popup.js
file:
document.getElementById('btnOpenTab').onclick = sendMessage;