Chrome扩展程序修改newtab页面正文?

时间:2016-03-22 07:12:07

标签: javascript google-chrome google-chrome-extension

我有Chrome扩展程序,它为页面正文添加了新的div。但是当我试图在newtab页面上运行它时,它不起作用。

这是我的 background.js

/* regex should match the following:
*  {{#if}}, {{#elif}}, {{#else}}, {{/if}}
* the second group makes it so it should be able to find additional arguments if provided.
* e.g. {{#if someArgs}}
*/
var regex = /{{\s*(#if|elif|else|\/if)\s*([^{\n]+)*}}/g
var data = $("#tmpl-test").html()
var matches

//<-----CONTENT---->
//this content works, it has no added attribute tag
var content = "<div id='tmpl-test' style='display:none'>{{#setPartial menu}}<ul>{{#each ~ as elName, el}}{{#if el.isDocObject}}<li><a>{{elName}}</a>{{#if el.Constructor}}<a>Constructor</a>{{/if}}</li>{{else}}<li class='group-{{elName}}'><h5>{{elName}}</h5>{{#partial menu, el}}</li>{{/if}}{{/each}}</ul>{{/setPartial}}{{#partial menu, ~}}</div>"

//here I added a style attribute to li..e.g. <li style='color:#ff0000'>...this regex explodes into an infinite loop
var content_that_will_cause_infinite_loop = "<div id='tmpl-test' style='display:none'>{{#setPartial menu}}<ul>{{#each ~ as elName, el}}{{#if el.isDocObject}}<li style='color:#ff0000'><a>{{elName}}</a>{{#if el.Constructor}}<a>Constructor</a>{{/if}}</li>{{else}}<li class='group-{{elName}}'><h5>{{elName}}</h5>{{#partial menu, el}}</li>{{/if}}{{/each}}</ul>{{/setPartial}}{{#partial menu, ~}}</div>"
//<-----END CONTENT---->

//#1: -----> works!
 console.log("minified html (no attribute):\n----------\n")
while (matches = regex.exec(content)){
  console.log(matches)
}


/*
//#2: ----> DEADLY! hangs up when added the style attribute..careful now...

 console.log("minified html w/ style attribute:\n----------\n")
while (matches = regex.exec(content_that_will_cause_infinite_loop)){
  console.log(matches)
}
*/

//#3:----> works with attribute, but html is multi-line i.e. expanded! weird huh?
 console.log("expanded html w/ style attribute:\n----------\n")
while (matches = regex.exec($("#tmpl-test").html())){
console.log(matches)
}

1 个答案:

答案 0 :(得分:0)

我发现可以通过添加内容脚本并在浏览器上单击扩展图标后向其发送消息来解决此问题。

<强> background.js:

aws ec2 describe-instances

<强> contentScript.js:

chrome.browserAction.onClicked.addListener(function(tab) {  
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    var url = tabs[0].url;
    if (url.indexOf('chrome://newtab') > -1) {
        chrome.tabs.query({active: true, currentWindow: true},     function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {someObject: someValue});
        });
    }
}); });