我正在尝试使用JS的Chrome扩展程序从脚本标签中提取“ webId%22:%22” var字符串。我当前使用的示例允许我提取页面标题。
{
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId1**] )"
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId2**] )"
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId3**] )"
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId4**] )"
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId5**] )"
"@odata.id":"[Organization URI]/api/data/v9.0/roles( [**roleId6**] )"
}
我要提取的是下面的webID:
// payload.js
chrome.runtime.sendMessage(document.title);
// popup.js
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('pagetitle').innerHTML = message;
});
//HTML popup
<!doctype html>
<html>
<head>
<title>WebID</title>
<script src="popup.js"></script>
<script src="testButton.js"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<p id="body"></p>
<h3>It's working</h1>
<p id='pagetitle'>This is where the webID would be if I could get this stupid thing to work.</p>
</body>
</html>
答案 0 :(得分:0)
您在onclick
属性中无法使用内联代码,请参见this answer。
您可以在devtools控制台中看到针对弹出窗口的错误消息:右键单击它,然后单击“检查”。
最简单的解决方案是在popup.js文件中附加一个click
侦听器。
弹出窗口是扩展页面,因此它可以直接访问chrome.tabs.executeScript,而无需chrome.extension.getBackgroundPage(),只是不要忘记在manifest.json中添加必要的权限,最好是“ { {3}}”。
对于这样的简单数据提取,您甚至不需要单独的内容脚本文件或消息传递,只需在executeScript中提供code
字符串即可。
chrome.tabs.executeScript({
code: '(' + (() => {
for (const el of document.querySelectorAll('script[if="inlineJs"]')) {
const m = el.textContent.match(/"([^"]*%22webId%22[^"]*)"/);
if (m) return m[1];
}
}) + ')()',
}, results => {
if (!chrome.runtime.lastError && results) {
document.querySelector('p').textContent = decodeURI(results[0]);
}
});