das*_*eel 6 mysql xmlhttprequest google-chrome-extension
我喜欢单击我的 chrome 扩展程序,它会获取当前选项卡 url 并将其插入到 MySQL 数据库中。似乎我必须使用 xhr,但是我对它的工作原理一无所知。我也有点明白Chrome 扩展?网络应用程序 API ? MySQL。
到目前为止,我有一个可用的 chrome 扩展程序,它获取当前选项卡的 url 并显示它和一个连接到我的数据库的 php 文件。但是,我可以使用一些帮助将 url 变量连接到 Web API,然后再连接到我的 php 文件。
最后,我是一个新手,所以如果这被质疑得很差,我深表歉意。
编辑
这是我的代码和更多详细信息...
当前网址.js
//grab the current url
chrome.tabs.getSelected(null, function(tab) {
var tabId = tab.id;
tabUrl = tab.url;
document.write(tabUrl);
});
Run Code Online (Sandbox Code Playgroud)
弹出窗口.html
<!doctype html>
<html>
<head>
<script src="currentUrl.js"></script>
<script language="javascript" type="text/javascript">
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
插入数据库
<?php
$con=mysqli_connect("localhost","root","my_pw","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO urlHistory (Urls)
VALUES ('Url'");
mysqli_close($con);
?>
Run Code Online (Sandbox Code Playgroud)
清单文件
{
"manifest_version": 2,
"name": "Current Url",
"description": "Grab tab's current url",
"version": "1.0",
"browser_action": {
"default_icon": "url_icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs"
// dont't I have to put something here?
]
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 XHR 将 URL 发送到您的服务器,该服务器insertdb.php将在数据库中侦听和存储 URL。
有关相关概念的更多信息:
示例代码:(
以下代码仅用于演示,并未考虑基本概念,例如输入验证、用户授权/身份验证、错误处理等(所有这些对于生产就绪解决方案都是必不可少的)。)
在 insertdb.php 中:
<?php
if (isSet($_POST['url'])) {
$con = mysqli_connect('localhost', 'root', 'my_pw', 'my_db');
...
$stmt = mysqli_prepare($con, 'INSERT INTO urlHistory (Urls) VALUES (?)');
mysqli_stmt_bind_param($stmt, 's', $_POST['url']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($con);
}
?>
Run Code Online (Sandbox Code Playgroud)
在 background.js 中:
function sendCurrentUrl(url) {
var req = new XMLHttpRequest();
req.addEventListener('readystatechange', function (evt) {
if (req.readyState === 4) {
if (req.status === 200) {
alert('Saved !');
} else {
alert("ERROR: status " + req.status);
}
}
});
req.open('POST', 'https://your_domain/your/path/insertdb.php', true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send('url=' + encodeURIComponent(url));
}
chrome.browserAction.onClicked.addListener(function (tab) {
sendCurrentUrl(tab.url);
});
Run Code Online (Sandbox Code Playgroud)
在 manifest.json 中:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"permissions": [
"activeTab",
"https://your_domain/*"
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7870 次 |
| 最近记录: |