document.write in Chrome Extension

混江龙づ霸主 提交于 2020-01-04 05:34:22

问题


I'm new to this so please bear with me. I am trying to write a chrome extension that does the following:

  1. Detect www.website.com/anypage.html. If this website is detected, then do the following.
  2. Don't load the URL.
  3. Instead, write a blank document with a hyperlink to www.website.com/anypage.html?ie=UTF8

The script is set to run at document start (in the manifest).

Here is my code:

Detect URL:

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

Write blank document with link to the URL with the UTF8 encoding tag:

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

This doesn't work as expected, and just shows a blank page. Anyone have any ideas?

Thanks!


EDIT: Here is the full code:

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();
}

回答1:


The chrome content script has access to the DOM, so you could just replace the contents of the body element of the current page with a new node that has your anchor tag either using dom manipulation methods or innerHTML:

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

Please note, this assumes that the JavaScript that is doing the DOM manipulation was properly added for your Chrome extension as a "content script":

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

EDIT:

Here is the code I used to make it work for me locally:

manifest.json

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

content-script.js

document.body.innerHTML = "<a href='test'>test</a>";


来源:https://stackoverflow.com/questions/8858980/document-write-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!