Chrome扩展程序中的动态表单

时间:2016-06-24 02:36:53

标签: forms google-chrome-extension

我有一个简单的chrome扩展,当点击时会显示一个包含三个名为title,url和summary的字段的表单。使用chrome.runtime.sendmessage,扩展通过抓取document.title,window.location.href和window.getSelection()。toString()来填充字段。我能够将信息提交到URL并捕获数据库中的数据。

我想在表单中添加一个新的选择字段,但我希望在select字段中获取要从URL动态加载的选项(选项可能会经常更改,我宁愿不强迫我的用户使用更新扩展程序。是否可以动态地将选择字段添加到扩展程序中硬编码的表单?我尝试使用iframe标记加载具有选择代码的网址,但它不会提交。从URL中抓取整个表单不会自动填充表单。

这是使用编码到扩展名中的选项的工作版本的代码。我希望能够通过互联网动态填充可选择的选项。

的manifest.json:

            {
                "manifest_version": 2,
                "name": "Website Submission",
                "description": "This extension gets and submits website info.",
                "version": "1.02",
                "background": {
                    "scripts": ["event.js"],
                    "persistent": false
                },
                "browser_action": {
                    "default_icon": "icon.png",
                    "default_popup": "popup.html"
                },
                "permissions": [
                    "tabs", 
                    "http://*/*", 
                    "https://*/*"
                ]
            }

popup.html

            <!DOCTYPE html>
            <html>
                <head>
                    <style>
                        body { 
                            min-width: 420px; 
                            overflow-x: hidden; 
                            font-family: Arial, sans-serif; 
                            font-size: 12px; 
                        }
                        input, textarea { 
                            width: 420px; 
                        }
                        input#save { 
                            font-weight: bold; width: auto; 
                        }
                    </style>
                    <script src="popup.js"></script>
                    <title>Website Submission</title>
                </head>
                <body>
                    <h1>Website Submission</h1>
                    <form id="addbookmark">
                        <p><label for="title">Title</label><br />
                        <input type="text" id="title" name="title" size="50" value="" /></p>
                        <p><label for="url">Url</label><br />
                        <input type="text" id="url" name="url" size="50" value="" /></p>
                        <p><label for="summary">Summary</label><br />
                        <textarea id="summary" name="summary" rows="6" cols="35"></textarea></p>
                        <p><label for="tags">Tags</label><br />
                        <input type="text" id="tags" name="tags" size="50" value="" /></p>
                        <p><label for="summary">Category</label><br />
                        <select id="category" name="category" >
                          <option value="0">Select</option>
                          <option value="5">Technology</option>
                          <option value="7">Science</option>
                          <option value="4">Sports</option>
                          <option value="2">Gaming</option>
                          <option value="3">Politics</option>
                          <option value="6">Health</option>
                          <option value="1">World News</option>
                        </select></p>
                        <p>
                            <input id="save" type="submit" value="Submit" />
                            <span id="status-display"></span>
                        </p>
                    </form>
                </body>
            </html>

event.js

            // This function is called onload in the popup code
            function getPageDetails(callback) { 
                // Inject the content script into the current page 
                chrome.tabs.executeScript(null, { file: 'content.js' }); 
                // Perform the callback when a message is received from the content script
                chrome.runtime.onMessage.addListener(function(message)  { 
                    // Call the callback function
                    callback(message); 
                }); 
            };

content.js

            // Send a message containing the page details back to the event page
            chrome.runtime.sendMessage({
                'title': document.title,
                'url': window.location.href,
                'summary': window.getSelection().toString()
            });

content.js

            // This callback function is called when the content script has been 
            // injected and returned its results
            function onPageDetailsReceived(pageDetails)  { 
                document.getElementById('title').value = pageDetails.title; 
                document.getElementById('url').value = pageDetails.url; 
                document.getElementById('summary').innerText = pageDetails.summary; 
            }

            // Global reference to the status display SPAN
            var statusDisplay = null;

            // POST the data to the server using XMLHttpRequest
            function addBookmark() {
                // Cancel the form submit
                event.preventDefault();

                // The URL to POST our data to
                var postUrl = 'http://www.example.com/extension/quicksubmit.asp';

                // Set up an asynchronous AJAX POST request
                var xhr = new XMLHttpRequest();
                xhr.open('POST', postUrl, true);

                // Prepare the data to be POSTed by URLEncoding each field's contents
                var title = encodeURIComponent(document.getElementById('title').value);
                var url = encodeURIComponent(document.getElementById('url').value);
                var summary = encodeURIComponent(document.getElementById('summary').value);
                var tags = encodeURIComponent(document.getElementById('tags').value);
                var category = encodeURIComponent(document.getElementById('category').value);

                var params = 'title=' + title + 
                             '&url=' + url + 
                             '&summary=' + summary +
                             '&category=' + category +
                             '&keywords=' + tags;
                //alert(params);
                // Replace any instances of the URLEncoded space char with +
                params = params.replace(/%20/g, '+');

                // Set correct header for form data 
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                // Handle request state change events
                xhr.onreadystatechange = function() { 
                    // If the request completed
                    if (xhr.readyState == 4) {
                        statusDisplay.innerHTML = '';
                        if (xhr.status == 200) {
                            // If it was a success, close the popup after a short delay
                            statusDisplay.innerHTML = xhr.responseText;
                            //statusDisplay.innerHTML = 'Saved!';
                            window.setTimeout(window.close, 2000);
                        } else {
                            // Show what went wrong
                            statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
                        }
                    }
                };

                // Send the request and set status
                xhr.send(params);


                statusDisplay.innerHTML = 'Saving...';
            }

            // When the popup HTML has loaded
            window.addEventListener('load', function(evt) {
                // Cache a reference to the status display SPAN
                statusDisplay = document.getElementById('status-display');
                // Handle the bookmark form submit event with our addBookmark function
                document.getElementById('addbookmark').addEventListener('submit', addBookmark);
                // Get the event page
                chrome.runtime.getBackgroundPage(function(eventPage) {
                    // Call the getPageInfo function in the event page, passing in 
                    // our onPageDetailsReceived function as the callback. This injects 
                    // content.js into the current tab's HTML
                    eventPage.getPageDetails(onPageDetailsReceived);
                });
            });

0 个答案:

没有答案