2

我是新手,所以请多多包涵。我正在尝试编写一个执行以下操作的 chrome 扩展:

  1. 检测 www.website.com/anypage.html。如果检测到此网站,请执行以下操作。
  2. 不要加载网址。
  3. 相反,编写一个空白文档,其中包含指向 www.website.com/anypage.html?ie=UTF8 的超链接

该脚本设置为在文档开始时运行(在清单中)。

这是我的代码:

检测网址:

var regExp = /website.com/gi;
var match = 0;
testString = window.location.href.toString();
if(regExp.test(testString) { 
match = 1;

使用 UTF8 编码标签编写带有 URL 链接的空白文档:

document.write("<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>");

这不能按预期工作,只是显示一个空白页。有人有想法么?

谢谢!


编辑:这是完整的代码:

checklink(); // If there is a match, then checklink will return a 1. If it's already     tagged, it will return a 5.
var matchLink = null;
if (checklink() === 1) {
matchLink = window.location.href.toString();

if (checklink() != 1) {
matchLink = null;

function checklink() { //checks to see if the current URL matches website.com
var regExp = /website.com/gi,
testString = window.location.href.toString(),
match = 0,
tagged = 0;

if (regExp.test(testString)) { //if there is a match, returns 1
match = 1;


var regExp2 = /UTF8/gi;
if (regExp2.test(testString)) { //if UTF8 is found, then it returns 5
tagged = 5;

return(match + tagged);


function tagUTF() {
if (matchLink) {
var newLink = matchLink + "?ie=UTF8";
document.write("<a href=\"" + newLink + "\">Link</a>");


if (matchLink) {
tagUTF();
}
4

1 回答 1

2

chrome 内容脚本可以访问 DOM,因此您可以使用 dom 操作方法或 innerHTML 将当前页面的 body 元素的内容替换为具有您的锚标记的新节点:

document.body.innerHTML = "<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>";

请注意,这假设执行 DOM 操作的 JavaScript 已作为“内容脚本”正确添加到您的 Chrome 扩展程序中:

http://code.google.com/chrome/extensions/content_scripts.html

编辑:

这是我用来使它在本地为我工作的代码:

清单.json

{
  "name": "Test",
  "version": "1.0",
  "description": "Test",
  "permissions": [
    "<all_urls>"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_end"
    }
  ]
}

内容脚本.js

document.body.innerHTML = "<a href='test'>test</a>";
于 2012-01-14T08:12:38.720 回答