Yang Lu
Yang Lu

Reputation: 13

Clicking the button isn't calling the function?

Just got around to try and create my own chrome extension, went through some tutorials online (new to HTML and JS), and decided to start off with a basic webpage opener.

The manifest loads fine, but at the moment clicking the "Open Windows" button in the popup doesn't do anything?

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Switch Popup</title>
<script type="text/javascript" src = "script.js"></script>
</head>

<body>
<h1>Open/Close</h1>
<input type=button value="Open Windows" onclick="open_win()">
</body>

</html>

Here is the separate script file

function open_win()
{
    var links = ['https://www.facebook.com', 'https://www.google.com'];

    for(var i = 0; i < links.length; i++)
    {
        chrome.tabs.create({url: links[i]});
    }
}

Upvotes: 0

Views: 82

Answers (1)

Yoichiro Tanaka
Yoichiro Tanaka

Reputation: 925

You cannot use the onclick attribute because of Content Security Policy. Instead, you need to use the addEventLinstener() to register your event handler:

HTML

<body>
<h1>Open/Close</h1>
<input id="btnOpenWindows" type="button" value="Open Windows">
</body>

JavaScript

function open_win()
{
    var links = ['https://www.facebook.com', 'https://www.google.com'];

    for(var i = 0; i < links.length; i++)
    {
        chrome.tabs.create({url: links[i]});
    }
}

var button = document.querySelector("#btnOpenWindows");
button.addEventListener("click", open_win);

Upvotes: 1

Related Questions